什么是 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]);
OR
fetch(URL, [options]);
参数
fetch() 方法有两个参数。
- URL - 需要发出请求的 API 端点。
- [options] − 一个可选参数。它是一个包含方法、标头等作为键的对象。
返回值
它返回 promise,你可以使用 'then...catch' 块或异步方式。
使用 'then...catch' 块
JavaScript fetch() API 返回 promise,你可以使用 'then...catch' 块。
按照下面的语法将 fetch() API 与 'then...catch' 块。
fetch(URL)
.then(data => {
// Handle data
})
.catch(err=> {
// Handle error
})
在上面的语法中,你可以处理 'then' 块中的 'data' 和 '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>
输出
{"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 得到满足。之后,我们再次使用 'await' 关键字和 data.json() 来停止函数的执行,直到它将数据转换为 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>
输出
{"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 – 您可以将具有此属性的 headers 传递给请求。
- redirect − 如果您希望用户在完成请求后重定向到其他网页,则可以使用 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 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 属性的 employee 对象。
此外,我们还创建了包含 method、headers 和 body 属性的 options 对象。我们使用 'POST' 作为方法的值,并在将其转换为字符串作为 body 值后使用 employee 对象。
我们使用 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', // 发出发帖请求
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()) // 获取响应
.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 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', // 更新记录
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()) // 获取响应
.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 message returned from the API is : Successfully! Record has been updated.
The data added is : {"name":"Lion","color":"Yellow","age":10}
示例(发出 DELETE 请求)
在下面的代码中,我们向给定的 URL 发出 'DELETE' 请求,以使用 fetch() API 删除特定数据。它返回带有成功消息的响应。
<html>
<body>
<div id = "output"> </div>
<script>
const output = document.getElementById("output");
let options = {
method: 'DELETE', // 删除记录
}
let URL = " https://dummy.restapiexample.com/api/v1/delete/2";
fetch(URL, options)
.then(res => res.json()) // 删除数据后,获取响应
.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 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 将多个选项传递给请求。