什么是axios?
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
axios实例属性和方法
Axios类
AxiosError
Cancel //取消发送请求
CancelToken //用来配合取消请求
all //处理并发请求,所有成功才算成功
spread
create //创建axios实例
defaults //默认的配置
delete、get、head、options
post、patch、put //对应的请求方法
interceptors
request 请求拦截
response 响应拦截
请求配置
{
baseURL: '', //用于拼接的地址
timeout:0, //请求超时时间,为0表示没有
headers: {} //自定义请求头
//请求前对参数进行处理
transformRequest: [function (data, headers) {
// 对 data 进行任意转换处理
return data;
}],
//对响应数据进行处理
transformResponse: [function (data) {
// 对 data 进行任意转换处理
return data;
}],
//get方式传参
params: {
ID: 12345
},
// 对params序列化
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
//post传参
data: {
firstName: 'Fred'
},
// `responseType` 表示服务器响应的数据类型,可以是'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // default
}
// `onUploadProgress` 允许为上传处理进度事件
onUploadProgress: function (progressEvent) {
},
// `onDownloadProgress` 允许为下载处理进度事件
onDownloadProgress: function (progressEvent) {
},
//请求状态码处于哪个范围为成功
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
请求拦截
//拦截请求
axios.interceptors.request.use(config =>{
},error => {
})
/ 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
axios的使用
函数模式
axios([config])
axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#head(url[, config])
axios#options(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])
响应结构
{
// `data` 由服务器提供的响应
data: {},
// `status` 来自服务器响应的 HTTP 状态码
status: 200,
// `statusText` 来自服务器响应的 HTTP 状态信息
statusText: 'OK',
// `headers` 服务器响应的头
headers: {},
// `config` 是为请求提供的配置信息
config: {}
request: {}
}