关于前端:Fetch-API速查表9个最常见的API请求

1次阅读

共计 2587 个字符,预计需要花费 7 分钟才能阅读完成。

对于 Fetch API 我置信你曾经用过它们很屡次了,然而你是否还记得语法?如果能防止在旧我的项目中寻找半年前应用过的特定申请的语法,岂不更好?

在本文中,我将列出 9 个最常见的 Fetch API 申请,在你遗记 API 的时候能够翻出来查看。​

为什么要应用 Fetch API?

现在,咱们被所有提供丑陋的 SDK 的服务宠坏了,这些 SDK 将理论的 API 申请抽象化,咱们只须要应用典型的语言构造来申请数据,而不关怀理论的数据交换。

然而,如果你所抉择的平台没有 SDK 怎么办?或者如果你同时构建服务器和客户端呢?在这些状况下,你须要本人解决申请,这就是应用 Fetch API 的办法。

应用 Fetch API 的简略 GET 申请

fetch('{url}').then(response => console.log(response));

应用 Fetch API 的简略 POST 申请

fetch('{url}', {method: 'post'}).then(response => console.log(response));

在 Fetch API 中应用受权令牌 (Bearer) 进行 GET

fetch('{url}', {
  headers: {'Authorization': 'Basic {token}'
  }
}).then(response => console.log(response));

在 Fetch API 中应用查问字符串数据进行 GET

fetch('{url}?var1=value1&var2=value2')
    .then(response => console.log(response));

在 Fetch API 中应用 CORS 进行 GET

fetch('{url}', {mode: 'cors'}).then(response => console.log(response));

在 Fetch API 中应用受权令牌和查问字符串数据进行 POST

fetch('{url}?var1=value1&var2=value2', {
  method: 'post',
  headers: {'Authorization': 'Bearer {token}'
  }
}).then(response => console.log(response));

在 Fetch API 中应用表单数据进行 POST

let formData = new FormData();
formData.append('field1', 'value1');
formData.append('field2', 'value2');

fetch('{url}', {
  method: 'post',
  body: formData
}).then(response => console.log(response));

在 Fetch API 中应用 JSON 数据进行 POST

fetch('{url}', {
  method: 'post',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({
    'field1': 'value1',
    'field2': 'value2'
  })
})
.then(response => console.log(response));

在 Fetch API 中应用 JSON 数据和 CORS 进行 POST

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 申请的后果

Fetch API 返回一个 Promise。这就是为什么我总是应用 .then() 和回调函数来解决响应的起因:

fetch(...).then(response => {// process the response}

然而,如果你处于异步函数中,也能够期待后果:

async function getData(){let data = await fetch(...);
   // process the response
}

当初让咱们看一下如何从响应中提取数据:

如何查看 Fetch API 响应的状态码

发送 POST,PATCH 和 PUT 申请时,咱们通常对返回状态代码感兴趣:

fetch(...).then(response => {if (response.status == 200){// all OK} else {console.log(response.statusText);
  }
});

如何获取 Fetch API 响应的简略值

某些 API 端点可能会发回应用你的数据创立的新数据库记录的标识符:

var userId;

fetch(...)
    .then(response => response.text())
    .then(id => {
        userId = id;
        console.log(userId)
    });

如何转换 Fetch API 响应的 JSON 数据

然而在大多数状况下,你会在响应注释中接管 JSON 数据:

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

正文完
 0