1、axios

比如常用的需求中,想要请求A接口的数据再去请求B接口的数据,axios的做法是需要先请求A接口,然后在A接口的成功的回调函数里面去请求B接口。
fetch使用的情况并不多,主要是由于存在兼容性问题,在企业中就不会作为首选的目标去开发。

fetch的出现主要是解决xhr(XmlHttpRequest)的,并不是去作为替代axios而存在。
在这里插入图片描述

2、fetch的兼容性解决方法

polyfill第三方库

fetch对于安卓5又或是IE8以上不支持,github上的第三方库polyfill对于这一类问题进行了完善,polyfill是怎么去实现填补这个空缺的呢?它其实只是在fetch请求不支持的时候又重新回过头使用的XHR去操作,在支持使用fetch的浏览器上就使用fetch去请求。

3、fetch的使用

先在本地创建一个json文件,然后通过fetch请求json文件中的数据,模拟调取接口中的json数据。
json数据:

{
    "status": 0,
    "data":
    {
        "films": [
        {
            "name": "小陈同学",
            "age": 23,
            "addr":"长沙市"
        },{
            "name": "张三",
            "age": 18,
            "addr":"湘潭市"
        },{
            "name": "李四",
            "age": 20,
            "addr":"广州市"
        },{
            "name": "王五",
            "age": 50,
            "addr":"北京市"
        }],
        "total": 4
    },
    "msg": "ok"
}

模拟请求:

在使用fetch调取数据时,第一个回调函数并非像axios一样直接请求了数据的,而是需要先对数据进行一步处理,然后处理成功后才再通过回调函数返回出去。

第一个回调函数中除了res.json()外,还有res.text(),text()的话是直接返回了文本出去了,而json()是将res转为json对象再返回出去的。

fetch('json/data.json').then(res => { 
    return res.json() 
}).then(data => {
    console.log(data);
})

在这里插入图片描述

4、fetch的get请求

json对象的数据格式

fetch('apiUrl').then(res => {
  return res.json()
}).then(data => {
   console.log(data);
})

text文本的数据格式

fetch('apiUrl').then(res => {
  return res.text()
}).then(data => {
   console.log(data);
})

5、fetch的post请求

urlencoded编码格式:

urlencoded 格式,又叫 form 格式、x-www-form-urlencoded格式,它是一种表单格式。
主要是通过键值对的形式组成,键和值之间用 = :name=xiaochen,多个键值对之间用 & :name=xiaochen&age=23

fetch("json/test.json", {
	method: "post",
	headers: {
		"Content‐Type": "application/x‐www‐form‐urlencoded"
	},
	credentials: 'include',
	body: "name=xiaochen&age=23"
}).then(res => res.json()).then(res => {
	console.log(res);
})

application/json编码格式:

body中需要使用JSON.stringify将对象转为字符串的格式传入

fetch("json/test.json", {
	method: "post",
	headers: {
		"Content‐Type": "application/json"
	},
	body: JSON.stringify({
		name: "xiaochen",
		age: 23
	})
}).then(res => res.json()).then(res => {
	console.log(res);
})