Axios的默认配置(碎片知识)

axios API

axios(config)

axios({
   method: 'Post',
   url: '/user/123',
   data: {
    //
   }  
})

axios(url[, config])

//默认发送一个GET request
axios('/user/123');

Request method aliases

别名,提供所有请求方法

axios.delete(url[, config])

axios.head(url[, config])

axios.post(url[, data[, config]])

例子:

axios.get('/user?id=123')
.then(response => {
   //handle success
})
.catch(err => {
  //handle error
})
.then(() =>{
// always executed
});

还可以:axios.get(url, config)

axios.get('/user', {
   paramis: {
      id: 123, 
   }
})
.then().catch().then();

甚至可以用ES2017:

async function getUser() {
  try{
     onst response = await axios.get('/user?id=123');
     console.log(response)
  }  catch (error) {
     console.error(error)  
  }
}

并发Concurrency

帮助函数处理并发请求。

axios.all(iterable)

axios.spread(callback)

function getUserAccount() {
  return axios.get('/user/123')  
}

function getUserPermissions() {
  return axios.get('/user/123/permisssions')  
}

axios.all([getUserAccount(), getUserPermissions()])
    .then(axios.spread(function(acct, perms) {
        //Both requexsts are now complete
     }))

创建一个实例用于客制化config

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
})

实例方法:

request, get, head,options, post, put, patch, getUri([config])

Request Config

常用配置:(全面的配置见git)

{
  url: ''/user',

  methods: 'get',

  //baseURL会放到url前面,除非url是全的url。
  //对axios的实例传递相对URl,使用baseURL会更方便。
  baseURL: 'https://some-domain.com/api/',

  //在请求数据被发送到服务器前改变要发送的data
  //只能用于put, post, pathc请求方法
  //在数组中的最后一个函数必须返回一个string, 或者一个实例(FormData, Stream, Buffer, ArrayBuffer)
  //也可以修改header对象。
  transformRequest: [function(data, headers) { 
    //写要改变数据的代码
    return data
  }]
//当响应数据返回后,在它传入then/catch之前修改它
transformResponse: [function(data) { //...; return data; }]
//客制
header: {...},

params: {
id: 123;
},
//要发送的请求body, 只用在put ,post, patch.
data: { //...}
//如果请求时间超过timeout,则终止这个请求。
timeout: 1000,
}

ResponseConfig

 

Config Defaults

指定默认的配置,用于每个请求。

全局

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';

实例默认配置:

//当创建实例时,设置默认配置。
const instance = axios.create({ baseURL: 'https://api.example.com' }) //选择默认 instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

Config order of precedence

实例的默认配置,可以修改。

//此时默认timeout是0
const instance = axions.create()
//改变设置实例的的配置。
instance.defaults.timeout = 2500;

当使用这个实例发送请求时,还可以改变实例的默认配置。

instance.get('/longRequest', {
  timeout: 5000
})

Interceptors

拦截请求或者响应,在它们被then.catch处理之前。

猜你喜欢

转载自www.cnblogs.com/chentianwei/p/10167397.html