Installing
npm install axios
Features 特征
- Make XMLHttpRequests from the browser
- Make http requests from node.js
- 支持Promise的方法
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- JSON数据的自动转换
- 客户端支持防止XSRF攻击
常用方法:
get:
axios.get('/user?ID=12345').then().catch();
或者
axios.get('/user', {
params: {
ID: 12345
}
}).then().catch
post:
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
}).then().catch()
并发请求:
function a(){
return axios.get('/x/1');
}
function b(){
return axios.get('/y/1');
}
axios.all([a(), b()]).then(axios.spread(function (acct, perms) {
// Both requests are now complete
}))
通过给axios传递配置发出请求
axios(config)
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
也可以是
axios(url[, config])
使用自定义配置创建axios的实例(用于封装fetch)
axios.create([config])
Request Config有哪些选项:
url:只有url是必须项
method:无特殊声明是get
baseURL:除非url是绝对路径,否则baseURL会在其前面,就是使用baseURL的时候,url可以方便的设置为相对路径
transformRequest:在请求数据发送到服务器前对其进行更改,这仅适用于请求方法“PUT”、“POST”和“PATCH”,还可以更改headers
transformRequest: [function (data, headers) {
// Do whatever you want to transform the data
return data;
}],
transformResponse:让res在返回给then/catch前进行更改
transformResponse: [function (data) {
// Do whatever you want to transform the data
return data;
}],
headers:是要发送的自定义头
params:是与请求一起发送的URL参数
params: {
ID: 12345
},
paramsSerializer:是一个可选函数,负责序列化'params'`
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
data:是作为请求主体发送的数据,只支持“PUT”、“POST”和“PATCH”请求方式
data: {
firstName: 'Fred'
},
timeout:指定请求超时前的毫秒数,超过超时时间,请求被中止
responseType: 'json', // default 服务器响应的数据类型
responseEncoding: 'utf8', // default 解码响应的编码
onUploadProgress:允许处理上载的进度事件
onUploadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
onDownloadProgress下载允许处理事件的进度
onDownloadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
maxContentLength:定义允许的http响应内容的最大大小(以字节为单位)
maxContentLength: 2000,
validateStatus:定义是解析还是拒绝给定HTTP响应状态代码的承诺。如果validateStatus
返回true
(或设置为null
或undefined
),则承诺将被解析;否则,承诺将被拒绝。
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
maxRedirects: 5,// default 定义node.js中要遵循的最大重定向数。
httpAgent\httpsAgent:在node.js中分别定义执行http和https请求时要使用的自定义代理。这允许添加默认情况下未启用的选项,如“keepAlive”。
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
proxy:定义代理服务器的主机名和端口。
cancelToken:取消令牌
Response Schema Response模式
请求的响应对象中包含以下信息。
data: {},是服务器提供的响应数据
status: 200,是服务器响应中的HTTP状态代码
statusText: 'OK',是来自服务器响应的HTTP状态消息
headers: {},服务器响应的标头
config: {},是为请求提供给“axios”的配置
request: {} request`是生成此响应的请求
当时用then方法时候,将要收到的响应内容
axios.get('/user/12345')
.then(function (response) {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});
全局axios默认值:
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';
自定义axios实例默认配置
const instance = axios.create({
baseURL: 'https://api.example.com'
});
配置的优先顺序:
配置将按优先顺序合并。顺序是lib/defaults.js中的库默认值,然后是实例的defaults属性,最后是请求的config参数。后者将优先于前者
请求拦截器和响应拦截器的处理
// Add a request interceptor 处理的是config
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor 处理的是res
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
如果需要给axios 的实例加上拦截器
const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
使用application/x-www-form-urlencoded格式:
默认情况下,axios将JavaScript对象序列化为JSON。要改为以application/x-www-form-urlencoded格式发送数据,可以使用qs库对数据进行编码:
const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));
axios是基于es6的Promise实现的
网友评论