Axios 简介
axios 是一个基于promise 的 HTTP 库,可以用在浏览器和 node.js 中。
- 从浏览器中创建
XMLHttpRequests
- 从 node.js 创建 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求数据和响应数据
- 取消请求
- 自动转换 JSON 数据
- 客户端支持防御 XSRF
cdn
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
实践
axios(config)
axios({
method:'post',
url: 'user/123',
data: {
username: 'wang',
password: '123456'
}
})
请求方法的别名
为方便起见,为所有支持的请求方法提供了别名
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
注: 在使用别名方法时, url
、method
、data
这些属性都不必在配置中指定。
并发
处理并发请求的助手函数
axios.all(iterable)
axios.spread(callback)
### 创建实例
可以使用自定义配置新建一个 axios 实例
axios.create([config])
let instance = axios.create({
baseURL:'https://example.com'
timeout:1000,
headers: {'X-custom-Header': 'foobar'}
})
设置全局的 axios 默认值
axios.defaults.baseURL="https://example.com"
....
拦截器
在请求或响应被 then
或 catch
处理前拦截它们。
//添加请求拦截器
axios.interceptors.request.use(function (config) {
//在发送请求之前做些什么
return config;
}, function (error) {
//对请求错误做些什么处理
return Promise.reject(error);
})
//添加响应拦截器
axios.interceptors.response.use(function (response) {
//对响应数据做点什么
return response;
}, function (error) {
//对响应错误做点什么
return Promise.reject(error);
})
如果你想在稍后移除拦截器,可以这样:
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
错误处理
axios.get('text.json')
.catch(error => {
if(error.response){
//请求已发出,但服务器响应的状态码不在 2xx 范围内
console.log(error.response.data);
console.log(error.response.status);//404错误什么的。
console.log(error.response.headers);
} else {
console.log('Error: ', error.message);
}
console.log(error.config);
})
可以使用 validateStatus
配置选项定义一个自定义 HTTP 状态码的错误范围。
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // 状态码在大于或等于500时才会 reject
}
})
取消
使用 cancel token 取消请求
可以使用 CancelToken.source
工厂方法创建 cancel token,像这样:
var CancelToken = axios.CancelToken;
var source = CancelToken.source();
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// 处理错误
}
});
// 取消请求(message 参数是可选的)
source.cancel('Operation canceled by the user.');
还可以通过传递一个 executor 函数到 CancelToken
的构造函数来创建 cancel token:
var CancelToken = axios.CancelToken;
var cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// executor 函数接收一个 cancel 函数作为参数
cancel = c;
})
});
// 取消请求
cancel();
Note : 可以使用同一个 cancel token 取消多个请求
axios 默认以 json 格式来传递数据,所以写 post 请求时,不像 jq 一样,还需要配置一下
// 全局设置 axios 请求头部
axios.defaults.headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
// 全局 axios 请求信息编码
axios.defaults.transformRequest = [function (data) {
let ret = ''
for (let it in data) {
ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
}
return ret
}];
encodeURIComponent(URIstring)
该方法返回 URIstring 的副本,其中的某些字符将被十六进制的转义序列进行替换。
该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ ' ( )
其他字作符(比如: ; / ? @ & = + $ , #
这些用于分隔 URI 组件的标点符号),都是由一个或多个十六进制的转义序列替换的。
跨域
axios 不支持 jsonp 跨域,如果需要使用 jsonp 需要单独引入 jsonp。
可以在 php 中设置
//允许所有域
header("Access-Control-Allow-Origin: *");
//允许某个域
header("Access-Control-Allow-Origin: http://example.com");