原文:How to Use Fetch to Make AJAX Calls in JavaScript,作者:Shruti Kapoor
在这个系列中,我将定期分享关于 JavaScript 的一些小知识点。我们将涵盖 JS 的基础知识、浏览器、DOM、系统设计、领域架构和框架。
Fetch 是一个在 JavaScript 中进行 AJAX 请求的接口。它被现代浏览器广泛实现,用于调用一个 API。
const promise = fetch(url, [options])
调用 fetch 会返回一个 promise,以及一个 response 对象。如果出现网络错误,promise 会被拒绝,如果连接到服务器没有问题,并且服务器回应了一个状态代码,promise 就会被处理。这个状态代码可能是 200s、400s 或 500s。
一个示例 FETCH 请求 -
fetch(url)
.then(response => response.json())
.catch(err => console.log(err))
默认情况下,请求是以 GET 方式发送的。要发送 POST / PATCH / DELETE / PUT,你可以使用方法属性作为 options
参数的一部分。options
可能使用其他一些可能的值 -
method
:例如 GET、POST、PATCHheaders
:标头对象mode
:例如cors
、no-cors
、same-origin
cache
:请求的缓存模式credentials
body
使用示例:
这个例子演示了 fetch 调用 API 和获取 git 仓库列表的用法。
const url = 'https://api.github.com/users/shrutikapoor08/repos';
fetch(url)
.then(response => response.json())
.then(repos => {
const reposList = repos.map(repo => repo.name);
console.log(reposList);
})
.catch(err => console.log(err))
要发送一个 POST 请求,下面是方法参数与 async / await 语法的使用方式。
const params = {
id: 123
}
const response = await fetch('url', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
});
const data = await response.json();