配置默认值

配置默认值

¥Config Defaults

你可以指定将应用于每个请求的配置默认值。

¥You can specify config defaults that will be applied to every request.

全局 axios 默认值

¥Global axios 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';

自定义实例默认值

¥Custom instance defaults

// Set config defaults when creating the instance
const instance = axios.create({
  baseURL: 'https://api.example.com'
});

// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

配置优先顺序

¥Config order of precedence

配置将按优先顺序合并。顺序先是 lib/defaults/index.js 中的库默认值,然后是实例的 defaults 属性,最后是请求的 config 参数。后者将优先于前者。这里有一个例子。

¥Config will be merged with an order of precedence. The order is library defaults found in lib/defaults/index.js, then defaults property of the instance, and finally config argument for the request. The latter will take precedence over the former. Here's an example.

// Create an instance using the config defaults provided by the library
// At this point the timeout config value is `0` as is the default for the library
const instance = axios.create();

// Override timeout default for the library
// Now all requests using this instance will wait 2.5 seconds before timing out
instance.defaults.timeout = 2500;

// Override timeout for this request as it's known to take a long time
instance.get('/longRequest', {
  timeout: 5000
});