温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

有哪些最常见的API请求

发布时间:2021-10-23 16:09:45 来源:亿速云 阅读:140 作者:iii 栏目:web开发

本篇内容介绍了“有哪些最常见的API请求”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

为什么要使用Fetch API?

如今,我们被所有提供漂亮的SDK的服务宠坏了,这些SDK将实际的API请求抽象化,我们只需要使用典型的语言结构来请求数据,而不关心实际的数据交换。

但是,如果你所选择的平台没有SDK怎么办?或者如果你同时构建服务器和客户端呢?在这些情况下,你需要自己处理请求,这就是使用Fetch  API的方法。

发送简单GET请求

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

发送简单POST请求

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

使用授权令牌进行GET

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

使用查询字符串数据进行GET

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

使用CORS进行GET

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

使用授权令牌和查询字符串数据进行POST

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

使用表单数据进行POST

let formData = new FormData(); formData.append('field1', 'value1'); formData.append('field2', 'value2');  fetch('{url}', {   method: 'post',   body: formData }).then(response => console.log(response));

使用JSON数据进行POST

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

使用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); }

“有哪些最常见的API请求”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

api
AI