Fetch API 完整指南
这并非你在许多网站上看到的普通博客文章。它新颖而令人惊叹。
fetch API 是一个基于 Promise 的JavaScript API,用于在浏览器中发出异步 HTTP 请求。
这是一个简单明了的 API,它使用 Promise 提供强大而灵活的功能集,用于从服务器获取资源。
如何使用 Fetch API?
使用 fetch API 非常简单。只需将 URL(即要获取的资源的路径)传递给 **fetch()** 方法即可。
fetch( 'URL' )
.then( red => {
// handle response data
})
.catch( err => {
// handle errors
});
阅读更多 =>解释 filter() 方法
发出 GET 请求
默认情况下,fetch API 使用 GET 方法进行异步请求。让我们来看一个非常简单的例子。这里我们将使用fetch()向“Dummy API”发出请求。
const url = "http://dummy.restapiexample.com/api/v1/employees";
fetchurl()
.then(res => {
console.log(res);
})
.catch(err => {
console.log('Error: ${err}' );
});
虚拟 API 是一个用于测试和原型设计的虚拟 API 服务。
发起帖子请求
Fetch 函数还可以用于请求中的任何其他 HTTP 方法:POST、PUT、DELETE、HEAD 和 OPTIONS。您只需在fetch()函数的选项中设置方法和请求体参数即可。
const url = 'http://dummy.restapiexample.com/api/v1/create'
const user = {
name: 'Rahul'
age: '16'
salary: '000'
};
const options = {
method: 'POST'
body: JSON.stringify(user),
}
fetch(url, options)
.then( res => res.json())
.then( res=> console.log(res));
阅读更多 => map() 方法详解
错误处理
` catch()`方法可以拦截请求执行过程中抛出的任何错误。但是,`fetch()` 返回的 Promise 对象不会拒绝 HTTP 错误,例如 404 或 500。为此,我们可以使用响应对象的 `ok` 属性。
const url = "http://dummy.restapiexample.com/api/v1/employee/40";
fetch(url) //404 error
.then( res => {
if (res.ok) {
return res.json( );
} else {
return Promise.reject(res.status);
}
})
.then(res => console.log(res))
.catch(err => console.log('Error with message: ${err}') );
获取和异步/等待
由于 fetch 是一个基于 Promis 的 API,我们可以更进一步,使用 ES2017 async/await 语法来简化我们的代码。
const url = 'http://dummy.restapiexample.com/api/v1/employees';
const fetchUsers = async () => {
try {
const res = await fetch(url);
// check for 404 error
if (!res.ok) {
throw new Error(res.status);
}
const data = await res.json();
console.log(data);
}
// catch block for network errors
catch (error) {
console.log(error);
}
}
fetchUsers( );
需要帮助,拜托了
我需要筹款购买一台机械键盘。疫情对我的家庭影响很大,所以我不能向我父亲要钱。请帮帮我。
⚡快乐编码|感谢您的阅读😀。文章来源:https://dev.to/rahxuls/complete-guide-to-fetch-api-3gla
