对于Fetch API我相信你已经用过它们不少次了,可是你是否还记得语法?若是能避免在旧项目中寻找半年前使用过的特定请求的语法,岂不更好?数据库
在本文中,我将列出9个最多见的Fetch API请求,在你忘记API的时候能够翻出来查看。json
现在,咱们被全部提供漂亮的SDK的服务宠坏了,这些SDK将实际的API请求抽象化,咱们只须要使用典型的语言结构来请求数据,而不关心实际的数据交换。api
可是,若是你所选择的平台没有SDK怎么办?或者若是你同时构建服务器和客户端呢?在这些状况下,你须要本身处理请求,这就是使用Fetch API的方法。服务器
fetch('{url}').then(response => console.log(response));
fetch('{url}', { method: 'post' }).then(response => console.log(response));
fetch('{url}', { headers: { 'Authorization': 'Basic {token}' } }).then(response => console.log(response));
fetch('{url}?var1=value1&var2=value2') .then(response => console.log(response));
fetch('{url}', { mode: 'cors' }).then(response => console.log(response));
fetch('{url}?var1=value1&var2=value2', { method: 'post', headers: { 'Authorization': 'Bearer {token}' } }).then(response => console.log(response));
let formData = new FormData(); formData.append('field1', 'value1'); formData.append('field2', 'value2'); fetch('{url}', { method: 'post', body: formData }).then(response => console.log(response));
fetch('{url}', { method: 'post', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ 'field1': 'value1', 'field2': 'value2' }) }) .then(response => console.log(response));
fetch('{url}', { method: 'post', mode: 'cors', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ 'field1': 'value1', 'field2': 'value2' }) }) .then(response => console.log(response));
Fetch API返回一个Promise。这就是为何我老是使用 .then()
和回调函数来处理响应的缘由:app
fetch(...).then(response => { // process the response }
可是,若是你处于异步函数中,也能够等待结果:cors
async function getData(){ let data = await fetch(...); // process the response }
如今让咱们看一下如何从响应中提取数据:异步
发送POST,PATCH和PUT请求时,咱们一般对返回状态代码感兴趣:async
fetch(...).then(response => { if (response.status == 200){ // all OK } else { console.log(response.statusText); } });
某些API端点可能会发回使用你的数据建立的新数据库记录的标识符:函数
var userId; fetch(...) .then(response => response.text()) .then(id => { userId = id; console.log(userId) });
可是在大多数状况下,你会在响应正文中接收JSON数据:post
var dataObj; fetch(...) .then(response => response.json()) .then(data => { dataObj = data; console.log(dataObj) });
请记住,只有在两个Promises都解决后,你才能访问数据。这有时会让人有点困惑,因此我老是喜欢使用async方法并等待结果。
async function getData(){ var dataObj; const response = await fetch(...); const data = await response.json(); dataObj = data; console.log(dataObj); }
这些示例应该涵盖了大多数状况。
我是否错过了什么,一个你天天都在使用的请求?或者是其余你正在苦恼的事情?请在评论区上告诉我。
最后,你也能够以可打印的形式得到这份备忘单:https://ondrabus.com/fetch-ap...
原文:https://blog.zhangbing.site
来源:https://www.freecodecamp.org做者:Ondrej Polesny