Using the CLI generated in vue2.x template has changed dramatically, the need to manually create a new directory at the same level main.tsinterceptors.ts
interceptors.ts
import axios from 'axios';
import router from './router';
// axios配置
axios.defaults.timeout = 6000;
axios.defaults.baseURL = 'http://192.168.7.69:8000';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// 设定请求头内容格式为form
// http request 拦截器
axios.interceptors.request.use(
config =>{
if (localStorage.token){ // 判断token是否存在
config.headers.Authorization = localStorage.token;
}
return config;
},
error => {
return Promise.reject(error)
}
);
// http response 拦截器
axios.interceptors.response.use(
response =>{
return response
},
error => {
if (error.response.data.result === 2){
// 这里是http请求失败后的返回判断,根据个人情况判断
router.replace('/login')
.then(
r =>{
localStorage.clear();
error.message = '身份已过期,请重新登录';
}
);
}else {
return Promise.reject(error)
}
}
);
router.beforeEach(((to, from, next) => {
if (to.meta.requireAuth){ //判断该路由是否需要登陆权限
if(localStorage.token){ //token存在
next()
}else {
next( // token不存在
{
path:'/login',
query:{
redirect:to.fullPath
}
}
)
}
}else { //如果不需要权限校验,直接跳转
next()
}
}));
export default axios;
main.ts
Introducing the interceptor main.ts
import axios from './interceptors';
Adding to the VUE property
Vue.use(VueAxios,axios);
In the place of use
this.axios.get('') // get请求
Storage token to localstorage
After a successful login
window.localStorage["token"] = res.data.token
Qs #### using setting request form form thereof
Some say the Internet qs included in axios but I can not import when in use. Prompted to download @types/qs
, then after the import modules
import QS from 'qs'
application:
let reqData = {
username:this.ruleForm.username,
password:md5(this.ruleForm.password)
};
this.axios.post("/login",QS.stringify(reqData))
.then()
It describes some basic use, to explore specific questions please leave a message!