Skip to content
On this page

FETCH

FETCH 不是 AJAX,它诞生的目的是为了代替 AJAX,它是 JS 中内置的 API:基于 FETCH 可以实现客户端和服务器端的信息通信

1.FETCH 是 ES2018 规范中新增的 API,所以浏览器的支持度不是特别好(可以基于 BABEL 的最新语法解析包,把其进行解析),想要兼容性好一些,需要使用 “fetch polyfill”

2.使用 FETCH 发送请求 => GET/HEAD 等请求不能设置 BODY => 不管服务器返回的状态是多少,FETCH 都不认为是失败(那怕是 4 或者 5 开头的状态码),都执行的是 THEN 中的方法(需要我们自己进行异常抛出处理)

demo

javascript
fetch('https://www.easy-mock.com/mock/5b0412beda8a195fb0978627/temp/info2', {
    method: 'GET',
    headers: {
        //=> 设置请求头
        'content-type': 'x-www-form-urlencoded'
    },
    // => 不管同源还是跨域请求都带着COOKIE信息
    credentials: 'include'
}).then(result => {
    console.log(result);
    /!*
        * headers{} 包含响应头信息
        * redirectedfalse 是否重定向
        * status状态码
        * statusText
        * type'basic'/'cors'
        * url请求的地址
        *
        * __proto__:Response
        *   arrayBuffer()
        *   blob()
        *   json()
        *   text()
        *   ...
        *   基于这些方法可以快速的把从服务器获取的结果找到
        *!/
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
javascript
fetch("https://www.easy-mock.com/mock/5b0412beda8a195fb0978627/temp/info")
  .then((result) => {
    let { status } = result;
    if (/^(4|5)\d{2}$/.test(status)) {
      throw new Error("query data is error!");
      return;
    }
    return result.json();
  })
  .then((result) => {
    console.log(result);
  })
  .catch((msg) => {
    console.log(msg);
  });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
javascript
fetch("https://www.easy-mock.com/mock/5b0412beda8a195fb0978627/temp/add", {
  method: "POST",
  body: "a=1&b=2", //=>BODY中只支持字符串(GET请求还无法设置BODY)
})
  .then((result) => {
    let { status } = result;
    if (/^(4|5)\d{2}$/.test(status)) {
      throw new Error("query data is error!");
      return;
    }
    return result.json();
  })
  .then((result) => {
    console.log(result);
  })
  .catch((msg) => {
    console.log(msg);
  });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
沪ICP备20006251号-1