JavaScript - Fetch API
什么是 Fetch API?
JavaScript Fetch API 是一个 Web API,允许 Web 浏览器向 Web 服务器发出 HTTP 请求。JavaScript 中,Fetch API 是在 ES6 版本中引入的。它是 XMLHttpRequest (XHR) 对象的替代方案,用于向服务器发出"GET"、"POST"、"PUT"或"DELETE"请求。
浏览器的 window 对象默认包含 Fetch API。
Fetch API 提供了 fetch() 方法,可用于异步访问 Web 资源。
fetch() 方法允许您向服务器发出请求,并返回一个 Promise。之后,您需要解析该 Promise 才能从服务器获取响应。
语法
您可以按照以下语法在 JavaScript 中使用 fetch() API
window.fetch(URL, [options]); 或 fetch(URL, [options]);
参数
fetch() 方法接受两个参数。
URL − 您需要向其发出请求的 API 端点。
[options] − 它是一个可选参数。它是一个包含方法、标头等信息的对象,以键为键。
返回值
它返回一个 Promise,您可以使用"then...catch"块或异步方式解决该 Promise。
使用"then...catch"块处理 Fetch() API 响应
JavaScript fetch() API 返回一个 Promise,您可以使用"then...catch"块处理它。
请按照以下语法将 fetch() API 与"then...catch"块一起使用。
fetch(URL)
.then(data => {
// Handle data
})
.catch(err=> {
// Handle error
})
在上述语法中,您可以在"then"块中处理"数据",并在"catch"块中处理错误。
示例
在下面的代码中,我们使用 fetch() API 从给定的 URL 获取数据。它返回我们使用"then"块处理的 Promise。
首先,我们将数据转换为 JSON 格式。然后,我们将数据转换为字符串并将其打印在网页上。
<html>
<body>
<div id = "output"> </div>
<script>
const output = document.getElementById('output');
const URL = 'https://jsonplaceholder.typicode.com/todos/5';
fetch(URL)
.then(res => res.json())
.then(data => {
output.innerHTML += "The data from the API is: " + "<br>";
output.innerHTML += JSON.stringify(data);
});
</script>
</body>
</html>
输出
The data from the API is:
{"userId":1,"id":5,"title":"laboriosam mollitia et enim quasi adipisci quia provident illum","completed":false}
异步处理 Fetch() API 响应
您还可以使用 async/await 关键字异步解决 fetch() API 返回的 Promise。
语法
用户可以按照以下语法将 async/await 关键字与 fetch() API 结合使用。
let data = await fetch(URL); data = await data.json();
在上面的语法中,我们使用了"await"关键字来停止代码执行,直到 Promise 被满足为止。之后,我们再次在 data.json() 中使用 'await' 关键字来暂停函数的执行,直到它将数据转换为 JSON 格式。
示例
在下面的代码中,我们定义了 getData() 异步函数,它使用 fetch() API 从给定的 URL 获取待办事项列表数据。之后,我们将数据转换为 JSON 格式,并在网页上打印输出。
<html>
<body>
<div id = "output"> </div>
<script>
async function getData() {
let output = document.getElementById('output');
let URL = 'https://jsonplaceholder.typicode.com/todos/6';
let data = await fetch(URL);
data = await data.json();
output.innerHTML += "The data from the API is: " + "<br>";
output.innerHTML += JSON.stringify(data);
}
getData();
</script>
</body>
</html>
输出
The data from the API is:
{"userId":1,"id":6,"title":"qui ullam ratione quibusdam voluptatem quia omnis","completed":false}
使用 Fetch() API 的选项
您还可以将对象作为第二个参数传递,其中包含以键值对形式呈现的选项。
语法
请按照以下语法将选项传递给 Fetch() API。
fetch(URL, {
method: "GET",
body: JSON.stringify(data),
mode: "no-cors",
cache: "no-cache",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
redirect: "follow",
})
选项
这里,我们提供了一些传递给 fetch() API 的选项。
method − 根据您要发起的请求类型,接受 'GET'、'POST'、'PUT' 和 'DELETE' 方法作为值。
body − 用于将数据传递到字符串格式。
mode − 出于安全原因,接受 'cors'、'no-cors'、'same-origin' 等值。
cache − 接受 '*default'、'no-cache'、'reload' 等值。
credentials − 接受'same-origin'、'omit' 等值。
headers − 您可以将具有此属性的标头传递给请求。
redirect − 如果您希望用户在完成请求后重定向到另一个网页,可以使用重定向属性。
示例:发出 GET 请求
在下面的代码中,我们将"GET"方法作为选项传递给 fetch() API。
Fetch() API 从给定的 API 端点获取数据。
<html>
<body>
<div id = "output"> </div>
<script>
let output = document.getElementById("output");
let options = {
method: 'GET',
}
let URL = "https://dummy.restapiexample.com/api/v1/employee/2";
fetch(URL, options)
.then(res => res.json())
.then(res => {
output.innerHTML += "The status of the response is - " + res.status + "<br>";
output.innerHTML += "The message returned from the API is - " + res.message + "<br>";
output.innerHTML += "The data returned from the API is - " + JSON.stringify(res.data);
})
.catch(err => {
output.innerHTML += "The error returned from the API is - " + JSON.stringify(err);
})
</script>
</body>
</html>
输出
The status of the response is - success
The message returned from the API is - Successfully! Record has been fetched.
The data returned from the API is - {"id":2,"employee_name":"Garrett Winters","employee_salary":170750,"employee_age":63,"profile_image":""}
示例(发出 POST 请求)
在下面的代码中,我们创建了包含 emp_name 和 emp_age 属性的员工对象。
此外,我们还创建了包含方法、标头和正文属性的选项对象。我们使用"POST"作为方法的值,并将员工对象转换为字符串后用作正文值。
我们使用 fetch() API 向 API 端点发出 POST 请求以插入数据。发出 POST 请求后,您可以在网页上看到响应。
<html>
<body>
<div id = "output"> </div>
<script>
let output = document.getElementById("output");
let employee = {
"emp_name": "Sachin",
"emp_age": "30"
}
let options = {
method: 'POST', // To make a post request
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(employee)
}
let URL = "https://dummy.restapiexample.com/api/v1/create";
fetch(URL, options)
.then(res => res.json()) // Getting response
.then(res => {
output.innerHTML += "The status of the request is : " + res.status + "<br>";
output.innerHTML += "The message returned from the API is : " + res.message + "<br>";
output.innerHTML += "The data added is : " + JSON.stringify(res.data);
})
.catch(err => {
output.innerHTML += "The error returned from the API is : " + JSON.stringify(err);
})
</script>
</body>
</html>
输出
The status of the request is : success
The message returned from the API is : Successfully! Record has been added.
The data added is : {"emp_name":"Sachin","emp_age":"30","id":7425}
示例(发出 PUT 请求)
在下面的代码中,我们创建了"animal"对象。
此外,我们还创建了 options 对象。在 options 对象中,我们添加了"PUT"方法、标头和 animal 对象作为主体。
之后,我们使用 fetch() API 更新给定 URL 上的数据。您可以看到成功更新数据的输出响应。
<html>
<body>
<div id = "output"> </div>
<script>
let output = document.getElementById("output");
let animal = {
"name": "Lion",
"color": "Yellow",
"age": 10
}
let options = {
method: 'PUT', // To Update the record
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(animal)
}
let URL = "https://dummy.restapiexample.com/api/v1/update/3";
fetch(URL, options)
.then(res => res.json()) // Getting response
.then(res => {
console.log(res);
output.innerHTML += "The status of the request is : " + res.status + "<br>";
output.innerHTML += "The message returned from the API is : " + res.message + "<br>";
output.innerHTML += "The data added is : " + JSON.stringify(res.data);
})
.catch(err => {
output.innerHTML += "The error returned from the API is : " + JSON.stringify(err);
})
</script>
</body>
</html>
输出
The status of the request is : success
The message returned from the API is : Successfully! Record has been updated.
The data added is : {"name":"Lion","color":"Yellow","age":10}
示例(发出 DELETE 请求)
在下面的代码中,我们使用 fetch() API 向给定的 URL 发出"DELETE"请求,以删除特定数据。它会返回包含成功消息的响应。
<html>
<body>
<div id = "output"> </div>
<script>
const output = document.getElementById("output");
let options = {
method: 'DELETE', // To Delete the record
}
let URL = " https://dummy.restapiexample.com/api/v1/delete/2";
fetch(URL, options)
.then(res => res.json()) // After deleting data, getting response
.then(res => {
output.innerHTML += "The status of the request is : " + res.status + "<br>";
output.innerHTML += "The message returned from the API is : " + res.message + "<br>";
output.innerHTML += "The data added is - " + JSON.stringify(res.data);
})
.catch(err => {
output.innerHTML += "The error returned from the API is : " + JSON.stringify(err);
})
</script>
</body>
</html>
输出
The status of the request is : success The message returned from the API is : Successfully! Record has been deleted The data added is - "2"
使用 Fetch() API 的优势
使用 fetch() API 与第三方软件或 Web 服务器交互有以下优势。
简单的语法 − 它提供了向服务器发出 API 请求的简单语法。
基于 Promise − 它返回 Promise,您可以使用"then...catch"块或"async/await"关键字异步执行该操作。
JSON 处理 − 它具有内置功能,可以将字符串响应数据转换为 JSON 数据。
选项 − 您可以使用 fetch() API 向请求传递多个选项。

