文章有参看其他博主文章:
- https://blog.csdn.net/weixin_43830606/article/details/88964522
- https://www.jianshu.com/p/636aa0e565a5
一、概述
1.为什么选择axios
- 随着 vuejs 作者尤雨溪发布消息,不再继续维护vue-resource,并推荐大家使用 axios 开始,axios 被越来越多的人所了解
2.axios特点
axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:
- 从浏览器中创建 XMLHttpRequest
- 支持node.js中发送http请求
- 支持 Promise API
- 拦截请求和响应(内置拦截器)
- 转换请求和响应数据
- 取消请求
- 自动转换JSON数据
- 客户端支持防御XSRF
二、安装axios
1.NPM方式
https://www.jianshu.com/p/cdec60909094
2.Bower安装
$ bower install axios
3.Js引入方式
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
三、使用
- 支持的请求方法别名
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]])
1.GET请求
-
通过问号拼接方式
// 向具有指定ID的用户发出请求 axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
-
通过params对象传递参数,通过此方式,框架会自动帮你拼接参数到链接末尾
axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
2.POST请求
-
发送data数据,默认为Content-Type为
application/x-www-form-urlencoded
,此时发送数据是以formData形式提交的axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
-
发送json格式数据
- 设置header头
// 参数1:url,参数2:data,参数3:headers // data参数还得变成json格式 var jsonData = { 'birthday':'1996-1-1', 'sex':'man' } axios.post("/userList",jsonData,headers:{'Content-Type':'application/json'}) .then(res=>{ console.log(res.data) }) .catch(error=>{ console.log(error) })
- 添加
qs
库,将json序列化之后传递
import axios from 'axios'; import qs from 'qs'; export default function request(url, params) { return axios.post(`https://xxxxxxxx/${url}`, qs.stringify(params)) .then((response) => { console.log('response', response); return response; }) .catch((error) => { console.log('error', error); return error; }); }
3.执行多个并发请求
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
// 对两个请求的参数进行分割处理
.then(axios.spread(function (acct, perms) {
// 两个请求现在都执行完成
}));
4.通过config配置参数发送请求
上面通过axios的请求方法别名方式发送了请求,其实axios还支持传入一个config配置对象,可以传入更多参数,更加灵活
// 发送一个 POST 请求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
常见的配置选项如下:
参数 | 说明 | 示例 |
---|---|---|
url | 请求路径 | url: ‘/user’ |
method | 请求方法 | method: ‘get’,默认为get |
baseURL | 基础路径 | baseURL: ‘https://xxx/api/’,baseURL 将自动加在 url 前面 |
transformRequest | 发送请求前的数据处理,只能用在 ‘PUT’, ‘POST’ 和 ‘PATCH’ 这几个请求方法 | transformRequest: [function (data) { // 对 data 进行任意转换处理 return data; }] |
transformResponse | 响应后数据处理,在传递给 then/catch 前,允许修改响应数据 | transformResponse: [function (data) { // 对 data 进行任意转换处理 return data; }] |
headers | 自定义请求头 | headers: {‘Content-Type’: ‘application/json’} |
params | 与请求一起发送的 URL 参数 | params: { ID: 12345 } |
paramsSerializer | 是一个负责 params 序列化的函数 | paramsSerializer: function(params) { return Qs.stringify(params, {arrayFormat: ‘brackets’}) } |
data | 作为请求主体被发送的数据,只适用于这些请求方法 ‘PUT’, ‘POST’, 和 ‘PATCH’ | data: { firstName: ‘Fred’ } |
timeout | 指定请求超时的毫秒数(0 表示无超时时间),超过 timeout 的时间,请求将被中断 | timeout: 1000 |
withCredentials | 表示跨域请求时是否需要使用凭证 | withCredentials: false,默认值 |
adapter | 允许自定义处理请求,以使测试更轻松 | adapter: function (config) { /* … */ } |
auth | 表示应该使用 HTTP 基础验证,并提供凭据,这将设置一个 Authorization 头,覆写掉现有的任意使用 headers 设置的自定义 Authorization 头 | auth: { username: ‘janedoe’, password: ‘s00pers3cret’ } |
responseType | 表示服务器响应的数据类型,可以是 ‘arraybuffer’, ‘blob’, ‘document’, ‘json’, ‘text’, ‘stream’ | responseType: ‘json’, // 默认的 |
其他不常使用参数:
参数 | 说明 | 示例 |
---|---|---|
xsrfCookieName | 用作 xsrf token 的值的cookie的名称 | xsrfCookieName: ‘XSRF-TOKEN’, // default |
xsrfHeaderName | 载 xsrf token 的值的 HTTP 头的名称 | xsrfHeaderName: ‘X-XSRF-TOKEN’, // 默认的 |
onUploadProgress | 允许为上传处理进度事件 | onUploadProgress: function (progressEvent) { // 对原生进度事件的处理 } |
onDownloadProgress | 允许为下载处理进度事件 | onDownloadProgress: function (progressEvent) { // 对原生进度事件的处理 } |
maxContentLength | 定义允许的响应内容的最大尺寸 | maxContentLength: 2000 |
validateStatus | 定义对于给定的HTTP 响应状态码是 resolve 或 reject promise 。如果 validateStatus 返回 true (或者设置为 null 或 undefined ),promise 将被 resolve; 否则,promise 将被 reject | validateStatus: function (status) { return status >= 200 && status < 300; // 默认的 } |
maxRedirects | 定义在 node.js 中 follow 的最大重定向数目,如果设置为0,将不会 follow 任何重定向 | maxRedirects: 5, // 默认的 |
httpAgent | 定义在执行 http时使用的自定义代理,keepAlive 默认没有启用 | httpAgent: new http.Agent({ keepAlive: true }) |
httpsAgent | 定义在执行 https时使用的自定义代理,keepAlive 默认没有启用 | httpsAgent: new https.Agent({ keepAlive: true }) |
proxy | 定义代理服务器的主机名称和端口,auth 表示 HTTP 基础验证应当用于连接代理,并提供凭据,这将会设置一个 Proxy-Authorization 头,覆写掉已有的通过使用 header 设置的自定义 Proxy-Authorization 头 | proxy: { host: ‘127.0.0.1’, port: 9000, auth: : { username: ‘mikeymike’, password: ‘rapunz3l’ } } |
四、使用拦截器
你可以截取请求或响应在被 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的自定义实例
var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
- 应用场景请参看此博客:https://www.jianshu.com/p/a0c67f4e145e
五、全局配置
1.全局配置
在js文件中引入了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';
2.自定义实例默认值
//在创建实例时设置配置默认值
var instance = axios.create({
baseURL:'https://api.example.com'
});
//在实例创建后改变默认值
instance.defaults.headers.common ['Authorization'] = AUTH_TOKEN;
六、创建实例
- axios除了可以通过全局使用外,还支持创建实例方式使用,即axios.create()
- 而之所以要创建axios实例,是因为我们实际工作项目中,可能需要访问多个服务地址,而这些服务请求和响应的结构也可能都完全不同,那么你可以通过axios.create创建不同的实例来处理。
- 比如axios1是用http状态码确定响应是否正常,而axios2是服务器自己定义的状态码,又或者他们请求头不同,支持的content-type不同,那么我可以单独为axios1和axios2写拦截器
1.创建一个实例
const instance1 = axios.create({
baseURL:'http://localhost:8080', //请求的域名,基本地址
timeout:5000, //请求的超时时长,单位毫秒
url:'/data.json', //请求的路径
method:'get,post,put,patch,delete' , //请求方法
headers:{
token:'' //比如token登录鉴权,请求的时候携带token,让后端识别登录人的信息
}, //请求头
params:{}, //请求参数拼接在URL上
data:{}, //请求参数放在请求体里
})
如果设置了全局的配置,但是又想在创建的实例里修改配置怎么办
instance.default.timeout = 3000
2.具体的使用
假如我们有两个请求接口,那么我们一般的做法是创建两个axios实例
const instance1 = axios.create({
baseurl:'http://localhost:8080',
timeout:'1000'
})
const instance2 = axios.create({
baseurl:'http://localhost:9090',
timeout:'3000'
})
//instance1这里用到的参数有 baseurl,timeout,method,url
instance1.get('/userinfo').then(res=>{
console.log(res)
})
//instance2这里用到的参数有 baseurl,timeout,method,url,params,并且对timeout进行了修改
instance1.get('/orderlist',{
timeout:'5000'
params:{}
}).then(res=>{
console.log(res)
})
七、解决跨域问题
- 开发环境如果要跨域,解决跨域问题(设置代理):vue-cli 3.0的在 package.json 同级目录新建一个 vue.config.js 文件,加入下面代码,其他版本找到配置文件的devServer加入代码
module.exports = {
//axios域代理,解决axios跨域问题
baseUrl: '/',
devServer: {
proxy: {
'': {
target: 'http://192.168.0.108:8090',
changeOrigin: true,
ws: true,
pathRewrite: {
}
}
}
}
}