大部分内容出自《axios官方文档》
什么是Axios?
Axios是一个基于promise的HTTP库,可以用在浏览器和node.js中。
Axios并不止适用于Vue,还可适用于其他项目中。
Axios的安装
1.npm安装:
npm install axios
执行命令后,在package.json中(这里以Vue项目为例)出现"axios":"版本号",则表示安装成功。给Vue量身定制的东西才需要在Vue中注册,例路由router,而axios非给Vue量身定制,在其他地方也能用,实质只是一个普通的插件。
2.使用cdn引入:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
使用axios之前:
当然要先引入axios。
可以在组件(.vue)中引入:
import axios from 'axios'
也可以在main.js中引入并定义实例property:
import axios from 'axios'
Vue.prototype.$axios = axios
如果需要在很多组件里用到某个数据/实用工具,但是不想污染全局作用域时,可以通过在原型上定义它们(Vue.prototype.$appName=''),使其在每个Vue的实例中可用。更多详细信息访问添加实例property
使用axios进行请求(以第二种axios引入方式为例):
1.向axios传递配置来创建请求
注:在请求过程中很有可能遇到跨域问题(发生在客户端与服务器之间),解决方案在:这里
① get请求
Ⅰ 第一种写法
this.$axios('/recipe/byclass', {
params: {
appkey: '6d62515547e6f191',
classid: 2,
start: 0,
num: 10
}
}).then(function (response) {
console.log(response)
})
Ⅱ 第二种写法
this.$axios({
method: 'get',
url: '/recipe/byclass',
params: {
appkey: '6d62515547e6f191',
classid: 2,
start: 0,
num: 10
}
}).then(function (response) {
console.log(response.data)
})
② post请求
this.$axios({
method: 'post',
url: '/recipe/byclass',
data: {
appkey: '6d62515547e6f191',
classid: 2,
start: 0,
num: 10
},
header:{
'Content-Type':'application/x-www-form-urlencoded'
}
}).then(function (response) {
console.log(response.data)
})
2.请求方法的别名(axios API)
为方便起见,为所有支持的请求方法提供了别名。
this.$axios.request({config})
this.$axios.get('url',{config})//{config}可选
this.$axios.delete('url',{config})//{config}可选
this.$axios.head('url',{config})//{config}可选
this.$axios.post('url',{data},{config})//{data}、{config}可选
this.$axios.put('url',{data},{config})//{data}、{config}可选
this.$axios.patch('url',{data},{config})//{data}、{config}可选
使用方式举例:
get()
this.$axios.get('/recipe/byclass', {
params: {
classid: '2',
start: 0,
num: 10,
appkey: '6d62515547e6f191'
}
}).then(function (response) {
console.log(response)
}).catch(function (error) {
console.log(error)
})
对于get请求来说,第二个参数({params})非必须,且第一个参数可以写成'地址?key=value&key1=value1'形式。
axios.get()结果是一个Promise,所以可以继续链式调用.then(()=>{})(请求成功后的回调函数)和.catch(()=>{})(请求失败后的回调函数)。
post()
this.$axios.post('/recipe/byclass', {
appkey: '6d62515547e6f191',
classid: 2,
start: 0,
num: 10
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
}).then(function (response) {
console.log(response)
}).catch(function (error) {
console.log(error)
})
使用自定义配置创建axios实例:
var instance = this.$axios.create({
baseURL:'/recipe',//如果使用了请求代理,这里就不需要写整个url
timeout:1000,//请求若超时,则取消请求
headers:{
'X-Custom-Header':'foobar'
}
})
创建的实例配置将和7个axios API中指定的配置合并。
axios请求配置:
1.局部请求配置
创建请求时可以用的配置选项(设置在axios实例配置或者axios API指定配置中都可以,因为最后都会合并到一起):
属性 | 含义 |
url(必须) | 用于请求服务器的URL |
method | 创建请求时使用的方法,默认为get |
baseURL | 将自动加在url前面,除非url是一个绝对URL 可以通过设置baseURL,便于为axios实例的方法传递相对URL |
transformRequest | 是一个数组,数组项是一个函数,该函数必须返回一个字符串或ArrayBuffer或Stream 允许在向服务器发送前,修改请求数据 只能用在PUT、POST、PATCH这几个请求方法 |
transformResponse | 是一个数组,数组项是一个函数,该函数必须返回一个字符串或ArrayBuffer或Stream 在传递给then/catch前,允许修改响应数据 |
headers | 即将被发送的自定义请求头 例:{'Content-Type':'application/json'} |
params | 即将与请求一起发送的URL参数 必须是一个无格式对象(plain object)或URLSearchParams对象 |
paramsSerializer | 是一个负责params序列化的函数 |
data | 作为请求体被发送的数据 只适用于PUT、POST、PATCH这些请求方法 在没有设置transformRequest时,data必须是以下类型之一: string、plain object、ArrayBuffer、ArrayBufferView、URLSearchParams 浏览器专属:FormData、File、Blob Node专属:Stream |
timeout | 指定请求超时的毫秒数(0 表示无超时时间) 若请求花费了超过timeout时间,请求将被中断 |
withCredentials | 默认值为false 表示跨域请求时是否需要使用凭证 |
adapter | 是一个函数,允许自定义处理请求,以使测试更轻松 返回一个promise并应用一个有效响应 |
auth | 表示应该使用HTTP基础验证,并提供凭据 这将设置一个Authorization头,覆写掉现有的任意使用headers设置的自定义Authorization头 |
responseType | 表示服务器响应的数据类型,可以是ArrayBuffer、Blob、Document、JSON、Text、Stream 默认格式为JSON |
xsrfCookieName | 用作xsrf token的值的cookie的名称 默认值为XSRF-TOKEN (csrf/xsrf 跨站请求伪造。一般是攻击者冒充用户进行站内操作,与XSS非常不同,XSS利用站点内的信任用户,而XSRF是伪装成受信任用户的请求来访问操作受信任的网站。详细信息可查看这里) |
xsrfHeaderName | 承载xsrf token的值的HTTP头的名称 默认值为X-XSRF-TOKEN |
onUploadProgress | 是一个函数 允许为上传 处理进度事件 |
onDownloadProgress | 是一个函数 允许为下载 处理进度事件 |
maxContentLength | 定义允许的相应内容的最大尺寸 |
validateStates | 是一个函数 定义对于给定HTTP响应状态码是resolve或reject promise 如果validateStatus返回true或设置为null或undefined,promise将被resolve,否则promise将被reject 默认值return status>=200&& status<300 |
maxRedirects | 定义在node.js中follow的最大重定向数目 默认值为5 若设置为0,将不会follow任何重定向 |
httpAgent httpsAgent |
分别在node.js中用于定义在执行http和https时使用的自定义代理 例:http(s)Agent:new http(s).Agent({keepAlive:true}) keepAlive默认没有启用(false) |
proxy |
定义代理服务器的主机名称和端口 auth表示HTTP基础验证应当用于连接代理,并提供凭据 将会设置一个Proxy-Authoriazation头,覆写掉已有的通过使用header设置的自定义Proxy-Authorization头 |
cancelToken |
用于取消请求的cancel token 例:cancelToken:new CancelToken(function (cancel{})) |
{
url: '',
method: 'get',
baseURL: '',
transformRequest: [function (data) {
return data;
}],
transformResponse: [function (data) {
return data;
}],
headers: {
'Content-Type': 'application/json'
},
params: {
name: '小红'
},
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
data: {
classid: 1
},
timeout: 1000,
withCredentials: false,
adapter: function (config) {
},
auth: {
username: 'xxx',
password: 'xxx'
},
responseType: 'json',
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
onUploadProgress: function (progressEvent) {
},
onDownloadProgress: function (progressEvent) {
},
maxContentLength: 2000,
validateStates: function (status) {
return status >= 200 && status < 300;
},
maxRediects: 5,
httpAgent: new http.Agent({keepAlive: true}),
httpsAgent: new http.Agent({keepAlive: true}),
proxy: {
host: '127.0.0.1',
port: 9000,
auth: {
username: 'xxx',
password: 'xxx'
}
},
cancelToken: new CancelToken(function (cancel) {
})
}
2.全局axios配置
this.$axios.defaults.baseURL = 'xxx'
this.$axios.headers.common['Authorization'] = 'xxx'
this.$axios.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
3.在axios实例创建后修改默认值
var instance = this.$axios.create({
baseURL: 'xxx'
});
instance.defaults.headers.common['Authorization'] = 'xxx'
4.配置优先顺序
配置会以一个优先顺序进行合并(后者覆盖前者)。
① 在lib/defaults.js找到的库的默认值
//使用由库提供的配置默认值来创建实例
var instance = this.$axios.create();
② 实例的defaults属性
instance.defaults.timeout = 2500;
③ 请求的config参数
instance.get('/recipe/byclass',{
timeout:5000
});
拦截器:
在请求或响应被then或catch处理前拦截它们。
1.添加拦截器
① 请求拦截(所有请求处理前被拦截)
this.$axios.interceptors.request.use(function (config) {
/*在发送请求前对配置做处理
* 对所有请求都生效*/
return config;//必须写,否则配置不生效
}, function (error) {
return Promise.reject(error);
})
② 响应拦截(所有数据返回后被拦截)
this.$axios.interceptors.response.use(function (response) {
/*对响应的数据做处理*/
/*axios获取返回结果:.then(function(response){response.data...}),而如果在这里返回response.data则可以直接使用*/
return response;
}, function (error) {
return Promise.reject(error);
})
③ 为自定义axios实例添加拦截器(请求拦截为例)
var instance = this.$axios.create();
instance.interceptors.request.use(function(){});
2.删除拦截器(请求拦截为例)
var myInterceptor = this.$axios.interceptors.request.use(function () {
});
this.$axios.interceptors.request.eject(myInterceptor);
错误处理:
this.$axios.get('xxx', {
/*【可选】可以使用validateStatus选项定义一个自定义HTTP状态码的错误范围,在错误范围时会进入.catch()*/
validateStatus: function (status) {
return status < 500;//status>=500时才会reject
}
}).then(function (response) {
}).catch(function (error) {
if (error.response) {
console.log(error.response.data);
} else {
console.log('Error', error.message);
}
console.log(error.config);
})
取消:
使用cancel token取消请求。可以使用同一cancel token取消多个请求。
1.使用CancelToken.source工厂方法创建cancel token
var CancelToken = this.$axios.CancelToken;
var source = CancelToken.source();
this.$axios.get('xxx',{
/*将cancel token和请求绑定,以便以后取消*/
cancelToken:source.token
}).catch(function (thrown){
if (this.$axios.isCancel(thrown)){
console.log('Request canceled',thrown.message);
} else{
//处理错误
}
});
/*取消请求 message参数可选*/
source.cancel('message');
2.传递executor函数到CancelToken的构造函数创建cancel token
var CancelToken = this.$axios.CancelToken;
var cancel;
this.$axios.get('xxx', {
/*CancelToken构造函数接收一个executor函数,该函数接收一个cancel函数(取消请求操作)作为参数,也就是c*/
cancelToken: new CancelToken(function executor(c) {
cancel = c;
})
});
/*取消请求(调用cancel函数)*/
cancel();