使用fetch更优雅的发起请求


使用fetch更优雅的发起请求

为什么要使用fetch呢?首先fetch天然支持promise,可以更好的处理请求状态。其次,fetch提供了多种处理数据的api,在携带或获取数据时更方便。最后fetch的api设计更加合理,使用起来更加方便。

下面学习一下fetch的基本用法

基本使用

首先看一下fetch api的基本用法

fetch('url', {})
    .then(response => response.json())  //默认发起get请求

fetch的第一个参数是请求的address,第二个参数是请求config,可以添加header等内容

显然,得益于fetch对promise的良好支持,可以很容易的发起请求。

config常用参数

method(默认GET)

string类型,支持常见的GET,POST,PUT等请求方式

mode(默认cors)

指定是否跨域,可选值有no-cors, cors, same-origin。如果请求url和当前资源在同一个域,建议用same-origin

cache(默认default)

cache会影响缓存,常用值有default, no-store, reload。

default情况下会先检测本地缓存是否有效,如果有效直接用本地缓存,若无效则请求服务器。

no-store直接请求服务器,不会使用本地缓存

reload会请求服务器,然后使用返回值刷新缓存

cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached

credentials(默认same-origin)

该属性用于指定是否携带cookie,常用值由same-origin(同源携带),omit(不带), include(携带)

tip: 在使用include时Access-Control-Allow-Origin不能是*,就算使用chrome extension也会失败

headers

请求header,必须指定携带数据为JSON字符串

headers: {
  'Content-Type':'application/json'
},

response对象

response对象提供了简洁易用的api用于获取状态和数据

  • status
    用于标识响应状态码,默认为200

  • statusText
    响应状态消息

  • ok
    用于确定状态码是否在200-299之间

注意事项

  • 当http状态码为404等错误是,promise状态依然是resolve,如果是网络错误或者跨域问题,promise状态会变为reject
  • fetch默认情况下不会发送跨域cookie,如果使用credentials: ‘include’指定跨域消息,则跨域header不能为*

示例

发送JSON数据

fetch('url', {
    method: 'POST', 
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
})
.then(response => response.json())
.catch((err) => {
  console.error(err);
});

tip:’Content-Type’: ‘application/json’用于指定发送数据为JSON字符串

上传表单

fetch('url', {
    method: 'POST',
    headers: {
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    body: "method=next"
}).then(async function(response){
    console.log(await response.json())
})

学习参考

https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch


Author: Maple
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint polocy. If reproduced, please indicate source Maple !
  TOC