对于FetchAPI我相信你已经用过很多次了,但你还记得语法吗?如果你能避免在旧项目中寻找你半年前使用的那些特定请求的语法不是更好吗?在本文中,我将列出9个最常见的FetchAPI请求,您可以在忘记API时查找。为什么要使用FetchAPI?这些天我们被所有提供好的SDK的服务宠坏了,这些SDK抽象出实际的API请求,我们只需要使用典型的语言结构来请求数据,而不关心实际的数据交换。但是,如果您选择的平台没有SDK怎么办?或者,如果您同时构建服务器和客户端怎么办?在这些情况下,您需要自己处理请求,这就是使用FetchAPI的方法。发送一个简单的GET请求fetch('{url}').then(response=>console.log(response));发送一个简单的POST请求fetch('{url}',{method:'post'}).then(response=>console.log(response));GETfetchwithauthorizationtoken('{url}',{headers:{'Authorization':'Basic{token}'}}).then(response=>console.log(回复));带有查询字符串数据的GETfetch('{url}?var1=value1&var2=value2').then(response=>console.log(response));GETfetchwithCORS('{url}',{mode:'cors'}).then(response=>console.log(response));POSTfetch('{url}?var1=value1&var2=value2',{method:'post',headers:{'Authorization':'Bearer{token}'}}).then(response=>console.log(response));为POSTlet使用表单数据formData=newFormData();formData.append('field1','value1');formData.append('field2','value2');fetch('{url}',{method:'post',body:formData}).then(response=>console.log(response));POSTfetchwithJSONdata('{url}',{method:'post',headers:{'Content-Type':'application/json'},body:JSON.stringify({'field1':'value1','field2':'value2'})}).then(response=>console.log(响应));带有JSON数据和CORS的POSTfetch('{url}',{method:'post',mode:'cors',headers:{'Content-Type':'application/json'},body:JSON.stringify({'field1':'value1','field2':'value2'})}).then(response=>console.log(response));如何处理FetchAPI请求的结果FetchAPI返回一个Promise,这就是为什么我总是使用.then()和回调函数来处理响应:fetch(...).then(response=>{//processtheresponse}但是如果你在一个异步函数中,也可以等待结果:asyncfunctiongetData(){letdata=awaitfetch(...);//processtheresponse}现在让我们看看如何从响应中提取数据:如何检查发送POST、PATCH和PUT请求时FetchAPI响应的状态代码,我们通常对返回状态代码感兴趣:fetch(...).then(response=>{if(response.status==200){//allOK}else{console.log(response.statusText);}});如何获取FetchAPI响应的简单值某些API端点可能会发回使用您的数据创建的新数据库记录的标识符:varuserId;fetch(...).then(response=>response.text()).then(id=>{userId=id;console.log(userId)});如何将JSON数据转换为FetchAPI响应但在大多数情况下在某些情况下,您将收到JSON数据响应文本:vardataObj;fetch(...).then(response=>response.json()).then(data=>{dataObj=data;console.log(dataObj)});请记住,您只能访问数据。这有时会让人有点困惑,所以我总是更喜欢使用异步方法并等待结果。asyncfunctiongetData(){vardataObj;constresponse=awaitfetch(...);constdata=awaitresponse.json();dataObj=data;console.log(dataObj);}总结这些例子应该涵盖大多数情况。我是否遗漏了什么,您每天使用的请求?或者您正在努力解决的其他问题?在评论部分让我知道。最后,您还可以获得可打印形式的备忘单:https://ondrabus.com/fetch-api-cheatsheet原文:https://www.freecodecamp.org/news/fetch-api-cheatsheet/作者:OndrejPolesny本文转载自微信公众号“前端全栈开发者”,可关注下方二维码。转载本文请联系前端全栈开发公众号。
