axios api

时间:2022-07-26
本文章向大家介绍axios api,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

别名请求方法

  • request( config )
  • get(url, config)
  • delete(url, config)
  • head(url, config)
  • options(url, config)
  • post(url, data, config)
  • put(url, data, config)
  • patch(url, data, config)

实例方法

  • request
  • get
  • delete
  • head
  • options
  • post
  • put
  • patch
  • getUri(conf)

请求配置

  • url '/user/:id' 请求地址
  • method 'get' 请求方法
  • beseURL 'https: //lh.con' 基础地址
  • transformRequest [ ...(data, headers) => data ] 发送拦截
  • transformResponse [...(data) => data] 返回拦截
  • headers { 'token': ' ...' } 请求头配置
  • params { id: 111 } 查询参数
  • paramsSerializer params => paramsString 查询参数序列化器
  • data { password: 123 } 提交数据

只适用于 PUT POST DELETE PATCH

  • timeout 1000 超时时间
  • withCredentials false 是否跨域
  • adapter (config) => {...} 自定义请求处理器,类似自定义 ajax发送器
  • auth { username: '', password: '' } 身份凭证
  • responseType 'json' 返回数据格式
  • responseEncoing 'utf8' 返回数据编码格式
  • xsrfCookieName ‘XSRF-TOKEN’ xsrf令牌值的cookie的名称
  • xsrfHeaderName 'X-XSRF-TOKEN'
  • onUploadProgress progressEvent => {...} 上传进度事件
  • onDownloadProgerss progressEvent => {...} 下载进度事件
  • maxContentLength 2000 最大内容长度
  • maxBodyLength 2000 最大请求体长度
  • validateStatus status 自定义状态校验器
  • maxRedirects 5 node.js 最大重定向次数
  • socketPath null UNIX套接字
  • httpAgent http代理
  • httpsAgent https代理
  • proxy 代理配置
  • cancelToken 取消令牌
  • decompress true 是否对响应体,解压缩

响应配置

  • data 响应体
  • status 状态码
  • statusText 状态描述
  • headers 响应头
  • config axios 请求配置
  • request 当前请求配置

全局默认配置

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

多级配置

// 默认全局配置
axios.defaults.timeout= 1000 * 6;
// 实例全局配置
instance = axios.create()
instance.defaults.timeout = 1000 * 3
// 请求配置
instance.get('/userName', {timeout: 1000 * 2})
// 优先级 global default < instance default < request 

拦截器

  • axios.interceptors.request.use( (config) => {} ) 添加请求拦截
  • axios.interceptors.request.eject( (config) => {} ) 移除请求拦截
  • axios.interceptors.response.use( (config) => {} ) 添加响应拦截
  • axios.interceptors.response.eject( (config) => {} ) 移除响应拦截

取消拦截

// 方式一
const source = axios.CancelToken.source() // 新建取消token
axios.get('/username', { cancelToken: source.token }) // 为请求添加取消标识
axios.post('/user', data, {cancelToken: source.token}) 
// 方式二
const CancelToken = axios.CencelToken
let cancel // 取消方法
axios.get('/username', {
   cancelToken: new CancelToken(c => cancel = c)
})
cancel()

文档

axios axios 中文文档