在安装完 axios
依赖之后,我们就可以开始使用,譬如:
js
import axios from 'axios'
axios(config)
其中,基本语法 axios(config)
的 config
是一个对象。主要包含以下参数:
js
axios({
// 请求路径
url: '/service/getlist',
// 请求方式 默认为GET
method: 'POST',
// 基础路径 如果url不是http绝对路径的话,真实的请求路径将是baseURL与url的拼接
baseURL: 'https://google.com',
/*
- 拼接到URL中,实际上就是QueryString的形式
- 是一个普通对象或者URLSearchParams对象
- 值为null or undefined的param,会被忽略。不会拼接到QueryString中
*/
params: {
ID: 12345
},
/*
参数序列化
可以利用[qs](https://github.com/ljharb/qs)将params进行定制序列化
[#5113](https://github.com/axios/axios/pull/5113)
新版变动:paramsSerializer需要设置为一个对象
{
encode: toString(encode)
serialize: serializeFn
}
*/
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'repeat'})
},
/*
该项表示请求体数据,只适用于 `POST`、`PUT`、`PATCH`、`DELETE` 请求方式。
没有设置transformRequest时,data的值必须是以下几种:
- string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
- Browser only: FormData, File, Blob
- Node only: Stream, Buffer
*/
data: {
firstName: 'Fred'
},
// 自定义请求头
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
// 转换请求参数
transformRequest: [function (data, headers) {
/** 处理请求体 **/
return data
}],
// 转换响应参数
transformResponse: [function (data) {
/** 处理响应体 **/
return data
}],
/*
适配器
可以看做是用来自定义response的一种方式
返回值必须是promise
*/
adapter: function (config) {},
/*
服务端响应数据类型,默认为json
- 'arraybuffer', 'document', 'json', 'text', 'stream', 'blob'
- browser only: 'blob'
- 相当于jquery.ajax配置中的dataType
*/
responseType: 'json',
/*
服务端响应数据编码类型 默认是utf-8
- Node.js only
- Ignored for `responseType` of 'stream' or client-side requests
*/
responseEncoding: 'utf-8',
// 超时时间 单位ms
timeout: 10000,
// 显示声明HTTP响应状态码的范围,以定义promise的resolve或reject操作
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// 监听上传进度
onUploadProgress: function (progressEvent) { // browser only
},
// 监听下载进度
onDownloadProgress: function (progressEvent) { // browser only
},
// 声明一个cancel token以供中止请求。在axios@^0.22.0版本以上 已被signal替代
cancelToken: new CancelToken(function (cancel) {
}),
// 声明一个signal以供中止请求。该方式的设置参考了fetch的中止方式
signal: new AbortController().signal,
/*
- 声明一个Basic模式的 Authorization,会自动添加到请求头中,并覆盖可能已有的Authorization请求头。
- 只支持Basic模式 想利用其他模式,可以手动声明 Authorization 请求头。
[Authorization](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization)
*/
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// xsrf防范机制 本地的cookie名
xsrfCookieName: 'XSRF-TOKEN', // default
// xsrf防范机制 要设置的请求头名称
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// `maxRedirects` defines the maximum number of redirects to follow in node.js.
// If set to 0, no redirects will be followed.
maxRedirects: 5, // default
// `socketPath` defines a UNIX Socket to be used in node.js.
// e.g. '/var/run/docker.sock' to send requests to the docker daemon.
// Only either `socketPath` or `proxy` can be specified.
// If both are specified, `socketPath` is used.
socketPath: null, // default
// `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
// and https requests, respectively, in node.js. This allows options to be added like
// `keepAlive` that are not enabled by default.
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// `proxy` defines the hostname, port, and protocol of the proxy server.
// You can also define your proxy using the conventional `http_proxy` and
// `https_proxy` environment variables. If you are using environment variables
// for your proxy configuration, you can also define a `no_proxy` environment
// variable as a comma-separated list of domains that should not be proxied.
// Use `false` to disable proxies, ignoring environment variables.
// `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
// supplies credentials.
// This will set an `Proxy-Authorization` header, overwriting any existing
// `Proxy-Authorization` custom headers you have set using `headers`.
// If the proxy server uses HTTPS, then you must set the protocol to `https`.
proxy: {
protocol: 'https',
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// `decompress` indicates whether or not the response body should be decompressed
// automatically. If set to `true` will also remove the 'content-encoding' header
// from the responses objects of all decompressed responses
// - Node only (XHR cannot turn off decompression)
decompress: true // default
})
TIP
上述的 config
相关参数中,只有 url
是必传项。