你可以指定將被用在各個(gè)請(qǐng)求的配置默認(rèn)值
axios.defaults.baseURL = 'http://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// 創(chuàng)建實(shí)例時(shí)設(shè)置配置默認(rèn)值
const instance = axios.create({
baseURL: 'https://api.example.com'
});
// 實(shí)例創(chuàng)建之后可修改默認(rèn)配置
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
配置會(huì)以一個(gè)優(yōu)先順序進(jìn)行合并。這個(gè)順序是:在 lib/defaults.js
找到的庫的默認(rèn)值,然后是實(shí)例的 defaults
屬性,最后是請(qǐng)求的 config
參數(shù)。后者將優(yōu)先于前者。這里是一個(gè)例子:
// 使用由庫提供的配置默認(rèn)值來創(chuàng)建實(shí)例
// 此時(shí)超時(shí)配置的默認(rèn)值是 0
const instance = axios.create();
// 覆寫庫的超時(shí)默認(rèn)值
// 現(xiàn)在,在超時(shí)前,所有請(qǐng)求都會(huì)等待 2.5 秒
instance.defaults.timeout = 2500;
// 為已知需要花費(fèi)很長(zhǎng)時(shí)間的請(qǐng)求覆寫超時(shí)設(shè)置
instance.get('/longRequest', {
timeout: 5000
});
更多建議: