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

fetch概念

fetch不是Ajax,它诞生的目的是为了代替Ajax,它是js中内置的API。

基于fetch可以实现客户端和服务端的信息通信

由于fetch是2018年提出,因此存在浏览器兼容问题。

1
2
3
4
5
fetch('https://v1.hitokoto.cn', {
method: 'GET',
}).then(result => {
console.log(result);
})
1
2
3
4
5
6
7
8
9
10
fetch('https://v1.hitokoto.cn', {
method: 'POST',
body: 'c=b',
headers: {
'Content-Type': 'x-www-form-urlcoded'
},
credentials: 'include'
}).then(result => {
console.log(result);
})

注意问题

  • GET/HEAD等请求不能设置body
  • 不管服务器返回的状态是多少,fetch都不认为是失败。并且会执行then方法。

返回结果

通过回调函数并不能直接获得响应结果。其返回结果为一个对象。

  • headers

    包含响应头信息

  • redirected

    是否重定向

  • status

    响应码

  • statusText

    响应文本

  • type

    basic/cors

  • url

    请求地址

image-20200823203137211

通过其提供的方法获取真正数据。