vue请求接口两种方式
第一种
this.$axios.post(url,data).then(res=> {
console.log(res)
}, response => {
console.log(response)
});
第二种
this.$axios.post(url,data).then(res=> {
console.log(res)
}
以下代码写在main.js
axios.interceptors.request.use(
config => {
// 判断是否存在X-Authorization,如果存在的话,则每个http header都加上token
if (localStorage.getItem("token")) {
config.headers["token"] ="token"+localStorage.getItem("token");
};
return config;
})
axios.interceptors.response.use(
res => {
console.log(res);
return res;
},
error => {
console.log(error);
}
)
从上面代码可以看见,第一种写法每次请求接口时都会有请求头和response来抛出异常,第二种方法将请求头和抛出异常返回写在了main.js里,这样每次在请求接口时就少了部分代码 看上去是不是很简洁粗暴呢!
热门推荐:
0