Vue uses the axios interceptor to add token + to set up cross-domain access in the header

Introduce axios

import axios from 'axios'
Vue.prototype.$http = axios;

At this point, axios has been installed in the project

Request method:

post方法:
this.$http.post(’/Api/test’, {
phone:this.userphone,
username:this.username
}).then((response) => {
console.log(response);
}).catch((error) =>{
console.log(error);
});

get method:
this.$http.get('/Api/test').then((response) => { console.log(response); }).catch((error) =>{ console.log(error) ; }); Save the token first, save the token in localStorage after successful login





localStorage.setItem(“token”, response.data.token);//存token
localStorage.getItem(“token”);//取token

1
2
Set up the interceptor Set up the interceptor
in main.js to realize that there is a token in the header of each request

axios.defaults.baseURL = '/proxy';//设置路由访问
axios.defaults.timeout = 30000;//设置超时时间
axios.interceptors.request.use(
    config => {
        console.log(config);
        if (localStorage.getItem("token")) {
            config.headers.Authorization = localStorage.getItem("token");
            //把localStorage的token放在Authorization里
        }
        return config;
    },
    function(err) {
        console.log("失败信息" + err);
    }
);

Guess you like

Origin blog.csdn.net/qq_45424679/article/details/115242512