从0实现一遍axios,再也不怕写请求

2022-12-22 0 234

axios允诺方式

主要就有get,post,put,patch,delete

post递交统计数据(配置文档递交+文档上载)put预览统计数据(将大部份统计数据均推放在服务器端)patch预览统计数据(只将修正的数据发送到后端)delete删掉统计数据

get方式

读法

初始化型

axios.get(/data.json).then((res)=>{ console.log(res) })

axios()型

axios({ method:get, url:/data.json }).then((res)=>{ console.log(res) })

params

假如他们须要读取 :

http://loc

初始化型

axios.get(/data.json,{ params:{ id:12 } }).then((res)=>{ console.log(res) })

axios()方式型

axios({ method:get, url:/data.json, params:{ id:12 } }).then((res)=>{ console.log(res) })

post方式

读法

初始化型

axios.post(/post,{},config)

post方式有三个参数,分别是url、统计数据、config。config参数暂时不讨论。

一般上载的统计数据分两种

form-data 配置文档递交(图片上载、文档上载)application/json以上两种统计数据,都可以在允诺发起后,进入浏览器network查看允诺头中的content-type进行查看

假设他们现在要上载一个统计数据:

let data = { id:12 }

那么他们可以直接将其传入:

axios.post(/post,data).then((res)=>{ console.log(res) })

1

2

3

4

axios()方式型

axios({ method:post, url:/post, data:data }).then(…)

1

2

3

4

5

6

两种统计数据的小细节

当他们上载的是一个一般的let data = { id:12 }统计数据时,Network的允诺头里会显示为:application/json;charset=UTF-8

当他们上载的是:

letdata = {id:12} let formData = new FormData() for(let key in data){ formData.append(key,data[key]) }

1

2

3

4

5

6

这里将data转格式了,格式变为formdata形式。

那么Network的允诺头里会显示为:

multipart/form-data; boundary=

—-WebKitFormBoundarywWFnSlPye1ZF8CSw

put方式和patch方式

形式与post方式大体相同,Network显示仅Request Method不同。

delete方式

读法

url删掉法

//直接从url里面删掉 axios.delete(/data.json,{ params:{ id:12 } }).then((res)=>{ console.log(res) })

1

2

3

4

5

6

7

8

9

从url删掉,Network允诺头最后面会显示为:Query String Parameters

允诺体删掉法

axios.delete(/data.json,{ data:{ id:12} }).then((res)=>{ console.log(res) })

1

2

3

4

5

6

7

8

从允诺体里删掉,Network允诺头最后面会显示为:Request Payload

两种方式的删掉方式是不同的,具体使用须要和后端沟通。

并发允诺

简介

同时进行多个允诺,并统一处理返回值。

案例:假设有一个聊天工具,同时有你的聊天记录和个人信息。此时须要初始化两个接口去允诺统计数据。此时须要统一处理他们的返回值。

axios提供的方式:all、spread

axios.all方式接受一个数组作为参数,数组中的每个元素都是一个允诺,返回一个promise对象,当数组中大部份允诺均已完成时,执行then方式。 在then方式中执行了 axios.spread 方式。该方式是接收一个函数作为参数,返回一个新的函数。接收的参数函数的参数是axios.all方式中每个允诺返回的响应。

function getUserAccount() {return axios.get(/user/12345); } function getUserPermissions() { return axios.get(/user/12345/permissions); } axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread((acct, perms) => { // 两个允诺都完成后,acct是getUserAccount的返回值,同理,perms是 getUserPermissions的返回值 }));

1

2

3

4

5

6

7

8

9

10

11

12

13

axios实例简介

为什么要用实例?

当他们须要用到不同的后端域名,直接初始化axios.get并不太方便。他们可以用创建实例的方式去初始化,不同的域名用不同的实例一一对应。

表现形式

created() { letinstance = axios.create({baseURL:http://localhost:8080,//基本允诺路径 timeout:1000,//超时设定}) instance.get(/data.json).then(res=>{ console.log(res) }) }

1

2

3

4

5

6

7

8

9

10

基本配置方式

baseURL:http://localhost:8080,//允诺的域名、基本地址 timeout:1000,//允诺超时时长(ms) url:/data.json,//允诺路径 method:get,post,put,patch,delete,//允诺方式 headers:{ token://代表当前登陆人的身份信息 },//设置允诺头 params:{},//将允诺参数拼接在url上,是一个对象 data:{}//将允诺参数放在允诺体里,是一个对象

其中,params和data表现形式为对象。

使用场景通常是发起允诺时,顺带传送参数:

//以get允诺为例,get有两个配置,分别是相对路径和config axios.get(/data.json,{ params:{ //参数 } })

参数配置方式

1.全局配置

axios.defaults.基本配置方式(baseurl等) 如: axios.defaults.timeout = 1000 //全局配置允诺时长1s

2.实例配置

let instance = axios.create( //基本配置方式 )

假如设置了全局的配置方式,而实例配置中没有设置相应的方式,则延用全局的方式,否则,以实例中的方式为主。

3.axios允诺配置

视具体情况而定,如初始化某个路径的文档巨大,他们可以单独对其允诺时长进行设置:

instance.get(/data.json,{ timeout:5000 })

总结

优先级:允诺配置 > 实例配置 > 全局配置

拦截器

在发起允诺前做一些处理,再发起允诺后再做一些处理。

分为允诺拦截器和响应拦截器

允诺拦截器

axios.interceptors.request.use( config=>{//在发送允诺前做些什么 return config }, err=>{ // 在允诺错误的时候做些什么(此处错误,允诺没有到后端) return Promise.reject(err)//这里返回一个promise对象 } )

响应拦截器

axios.interceptors.responce.use( res=>{ //允诺成功对响应统计数据进行处理 return res },err=>{ //响应错误做些什么(此处错误,到达后端后返回) return Promise.reject(err) } )

两者都在响应错误后进行了promise对象的返回,具体的作用是什么呢?

axios.get().then().catch(err=>{})

这一段代码是他们平时发送get允诺时的标准形态,then会执行允诺成功后的操作,catch用来捕获错误。

他们前面拦截响应后,无论是允诺还是响应的拦截器,他们的err返回的promise都会进入catch中。

取消拦截器(了解即可)

let inerceptors = axios.interceptors.request.use (config=>{ config.header = {auth:true } returnconfig }) axios.inerceptors.request.eject(interceptors)//用axios全局去初始化interceptors,这样就取消拦截了。。。

举个栗子

通过拦截器控制登陆状态

// 登陆状态,有token letrequest = axios.create({}) request.interceptors.request.use (config => { config.headers.token = return config }) // 非登陆状态,无token let request2 = axios.create({})

有token的可以访问更多,get更多的统计数据,无token则不行。类似于评论须要登陆

错误处理

表现形式

//首先设置拦截器axios.interceptors.request.use(config =>{ return config },err =>{ return Promise.reject(err) } ) axios.interceptors.response.use(res =>{ return res },err =>{ return Promise.reject(err) } ) axios.get(/data.json).then(res=>{ console.log(res) }).catch(err =>{ console.log(err) //大部份错误处理都会进入此处 })

具体的实践过程中,他们须要创建一个统一的错误处理,将大部份的错误类型都放在拦截其中,方便他们后面初始化接口时使用。

栗子

//创建一个允诺实例 letinstance = axios.create({})//为允诺实例添加允诺拦截器 instance.interceptors.request.use( config =>{ return config },err =>{ //允诺错误 一般http状态码以4开头,常见:401超时,404 not found 多为前端浏览器错误 return Promise.reject(err) } ) instance.interceptors.response.use(res=>{ return res },err =>{ //响应错误,一般http状态码以5开头,500系统错误,502系统重启等,偏向于服务器端返回的报错 return Promise.reject(err) } ) ​ //使用 instance.get(data).then(res=>{ console.log(res) }).catch(err =>{ console.log(err) })

取消允诺

用于取消正在进行的http允诺,比较少用到,就不做介绍了

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务