网络请求封装

159 阅读2分钟

方案:axios

特点:

  1. 允许在浏览器中xmlHttpRequest请求
  2. 允许在nide.js中发送http 请求
  3. 支持Promise API
  4. 支持拦截请求和响应,去做额外操作
  5. 转换请求和响应的数据等

支持多种请求方式:

  • axios(config)
  • axios.request(config)
  • axios.get(config)
  • axios.post(config)
  • axios.delete(config)
  • axios.head(config)
  • axios.put(config)
  • axios.patch(config)

简单使用:

默认get请求,根路径通过axios.defauts.baseUrl = ''设置

image.png

image.png

常见的config可配置项:

urlmethodbaseUrlparamsdatatimeoutheaderswithCredentialstransformRequesttransformResponseauthadapterresponseType
请求地址请求方式(默认get)根路径get请求的去query参数post请求的body参数超时设置自定义请求头header: {'token': 'rieurieruieruieuri123'}跨域是否带token(false)请求前的数据处理function(data){}请求后的数据处理function(data){}身份验证信息auth:{uname:'',pwd: ''}自定义请求处理 adapter:functiom(resolve,reject,config){}相应的数据格式 hson/blob/document/arraybuffer/text/stream

简单封装?

axios请求本身就是一个Promise,所以可以简单返回发起的请求调用,在页面通过then和catch回调

image.png

如何使用拦截器?

拦截器类型

  1. 请求成功
  2. 请求失败
  3. 响应成功
  4. 响应失败

什么时候需要请求拦截?

  • config中的信息不符合服务端要求
  • 比如每次发送请求里,需要增加一些loading动画,响应成功loading取消
  • 某些网络请求必须携带一些特殊信息,如token,或者特殊url,我们需要让用户先去登录,就可以在此处拦截

什么情况响应拦截?

  • 前端统一接口返回数据格式

请求拦截实现:

const instance = axios.create(config.baseConfig)
instance.interceptors.request.use(onFulfiled, onRejected)
  • onFulfiled: 请求成功拦截回调,参数为config,拦截处理后必须return config,否则调用方出现undefined
  • onRejected:请求失败拦截回调,参数为出现的error错误对象,出现的少

响应拦截实现:

const instance = axios.create(config.baseConfig)
instance.interceptors.request.use(onFulfiled, onRejected)
  • onFulfiled: 响应成功拦截回调,参数为接口返回的result,拦截处理后必须return result相关,否则调用方出现undefined
  • onRejected:响应失败拦截回调,参数为出现的error错误对象,响应失败,也应该return error相关信息,否则调用方出现undefined

demo:

1、页面发起axios 请求:

image.png 2、拦截器:

场景1: 写个不存在的接口url,触发响应失败拦截 image.png

查看拦截器的error和axios中的then回调打印res111

image.png

场景2: 请求拦截成功处理,不返回config,发现没调用接口

image.png 查看请求拦截中正常的config,以及没返回config后,调用方的res111,network没发起请求

image.png