https://github.com/axios/axios 官方文档教程很西详细,不在赘述。下面使用的简单举例以及注意事项。
直接使用axios
Get
可以不带参数,或参数直接拼到url中去,默认情况下走的是 application/x-www-form-urlencoded
import axios from "axios";
axios
.get("http://10.10.38.44:9007/api/v1/component/searchByName?name=背景框&exactly=false")
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
})
.finally(() => {
console.log("finally");
});
拼装get请求的参数:
axios
.get("http://10.10.38.44:9007/api/v1/component/searchByName", {
params: { name: "背景框" }
})
.then(response => {})
.catch(error => {})
.then(() => {
console.log("always executed");
});
Post
注意,此处和get请求的参数稍有区别{name:"背景框"}
vs { params: { name: "背景框" } }
, get请求的params
可以理解为修改url上的的kv参数。
post请求时,请求头默认为application/json;charset=utf-8
,和get请求时的也不同。
axios
.post("http://10.10.38.44:9007/api/v1/axios/postCommonWithParam", {
name: "背景框"
})
.then(response => {
console.log(response);
this.xData = response.data;
})
.catch(error => {
console.log(error);
});
若想让post请求传递的数据为application/x-www-form-urlencoded
格式的,可以有下面几种处理方法:
方法1、参数手动拼或者使用qs
将发送请求参数的json object改成key-value字符串的形式
1). 手动拼参数
let params = { name: "背景框" };
let ret = "";
for (let it in params) {
ret += encodeURIComponent(it) + "=" + encodeURIComponent(params[it]) + "&";
}
axios
.post("http://10.10.38.44:9007/api/v1/axios/postCommonWithParam", ret)
.then(response => {
})
.catch(error => {
});
2). 使用qs
对参数进行处理拼成key-value的形式
import Qs from "qs";
axios
.post(
"http://10.10.38.44:9007/api/v1/postCommonWithParam",
Qs.stringify({ name: "背景框" })
)
.then(response => {})
.catch(error => {});
let params = { name: "xx" };
const options = {
method: "POST",
data: Qs.stringify(params),
url: "http://10.10.38.44:9007/api/v1/axios/postCommonWithParam"
};
axios(options)
.then(response => {
console.log(response);
this.xData = response.data;
})
.catch(error => {
console.log(error);
});
可以在transformRequest中进行转换,调整为满足需要的格式(key-value)
举例1. 全局处理
axios.defaults.headers.common["Authorization"] = "AUTH_TOKEN_XXXX";
axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8";
axios.defaults.transformRequest = [
function(data) {
let ret = "";
for (let it in data) {
ret += encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
}
return ret;
}
];
举例2: 使用 Request Config 的情况
let params = { name: "xx1" };
const config = {
method: "POST",
data: params,
url: "http://10.10.38.44:9007/api/v1/axios/postCommonWithParam",
transformRequest: [
function(data) {
let ret = "";
for (let it in data) {
ret += encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
}
return ret;
}
]
};
axios(config)
.then(response => {
console.log(response);
this.xData = response.data;
})
.catch(error => {
console.log(error);
});
方法3、Request Config 使用params
传参
Request Config 配置中,params
配置的参数是通过修改url生效的(目测,待考证)。
使用params
代替data
实现同样的效果,虽然请求头没有修改为application/json
。
let params = { name: "xx1" };
const options = {
method: "POST",
params: params,
url: "http://10.10.38.44:9007/api/v1/axios/postCommonWithParam"
};
axios(options)
.then(response => {
})
.catch(error => {
});
axios的定制化
使用axios.create
初始化默认的配置,使用interceptors
拦截请求的发送与返回。
举例如下:示例参考自掘金:Vue二次封装axios为插件使用
export default function $axios(options) {
return new Promise((resolve, reject) => {
const instance = axios.create({
baseURL: process.env.VUE_APP_BASE_API,
headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" },
transformResponse: [],
timeout: 1000 * 15,
withCredentials: false
});
instance.interceptors.request.use(
config => {
if (store.getters.token) {
config.headers["th-token"] = store.getters.token;
}
return config;
},
error => {
if (error.code === "ECONNABORTED" && error.message.indexOf("timeout") !== -1) {
console.log("请求超时");
}
Promise.reject(error);
}
);
instance.interceptors.response.use(
res => {
if (res.data.succ) {
return res;
} else {
if (res.data.code === Code.UNAUTHEN || res.data.code === Code.SESSION_TIMOUT) {
MessageBox.confirm("你已被登出,可以取消继续留在该页面,或者重新登录", "确定登出", {
confirmButtonText: "重新登录",
cancelButtonText: "取消",
type: "warning"
}).then(() => {
store.dispatch("LogOut").then(() => {
location.reload();
});
});
} else {
Message({ message: res.data.msg, type: "error", duration: 5000 });
}
return Promise.reject(res);
}
},
err => {
console.error("request err: %o", err);
Message({ message: err.message, type: "error", duration: 5000 });
return Promise.reject(err);
}
);
});
}