axios-miniprogram/docs/pages/config/preview.md

5.2 KiB

默认配置

全局默认配置axios.defaults

axios.defaults.baseURL = 'https://www.api.com';
axios.defaults.headers.common['Accept'] = 'application/json, test/plain, */*';
axios.defaults.headers.post['Content-Type'] =
  'application/x-www-form-urlencoded; charset=utf-8';

自定义实例默认配置

可以创建时传递。

const instance = axios.create({
  baseURL: 'https://www.api.com',
  headers: {
    common: {
      Accept: 'application/json, test/plain, */*',
    },
    post: {
      'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
    },
  },
});

也可以创建后修改。

instance.defaults.baseURL = 'https://www.api.com';
instance.defaults.headers.common['Accept'] =
  'application/json, test/plain, */*';
instance.defaults.headers.post['Content-Type'] =
  'application/x-www-form-urlencoded; charset=utf-8';

配置优先顺序

发送请求时,会使用默认配置defaults和自定义配置config合并出请求配置requestConfig,然后用合并出的请求配置requestConfig去发送请求,多数情况下,后者优先级要高于前者,具体合并策略可以参考 mergeConfig.ts 的实现。

配置表

非全平台兼容的属性只会在平台支持的情况下生效。

参数 类型 默认值 说明 全平台兼容
adapter Function 查看 自定义适配器
baseURL String 基础地址
url String 请求地址
method String get 请求方法
params Object 请求参数
data String/Object/ArrayBuffer 请求数据
headers Object 查看 请求头
validateStatus Function 查看 自定义合法状态码
paramsSerializer Function 自定义参数序列化
transformRequest Function/Array<Function> 自定义转换请求数据
transformResponse Function/Array<Function> 自定义转换响应数据
errorHandler Function 自定义错误处理
cancelToken Object 取消令牌
timeout Number 10000 超时时间
dataType String json 响应数据格式
responseType String text 响应数据类型
enableHttp2 Boolean false 开启 http2
enableQuic Boolean false 开启 quic
enableCache Boolean false 开启 cache
sslVerify Boolean true 验证 ssl 证书