鍍金池/ 問(wèn)答/HTML/ axios 請(qǐng)求攔截?zé)o法生效?

axios 請(qǐng)求攔截?zé)o法生效?

1.主要是想統(tǒng)一配置tocken。但是實(shí)際配置似乎并不生效。
2.axios代碼如下

const Axios = axios.create({
    baseURL: "http://" + window.location.hostname + ":" + window.location.port + "/mallapi",
    timeout: 10000,
    responseType: "json",
    withCredentials: true, // 是否允許帶cookie這些
    // transformResponse:[function (data) {  
    //     return querystring.stringify(data)//轉(zhuǎn)換data 不用每個(gè)請(qǐng)求都用 querystring.stringify;
    // }],
    headers: {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
    }
});
Axios.interceptors.request.use(
    config => {
        // 在發(fā)送請(qǐng)求之前做某件事
        if (
            config.method === "post" ||
            config.method === "put" ||
            config.method === "delete"
        ) {
            // 添加token
            if (localStorage.getItem("joywareUser")) {
                config.data.accessToken = JSON.parse(localStorage.getItem("joywareUser")).accessToken;
                console.log(config.data.accessToken)
            };
            config.data = querystring.stringify(config.data);//將請(qǐng)求的參數(shù)轉(zhuǎn)化
        }
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject("請(qǐng)求攔截報(bào)錯(cuò)信息"+error);
    }
);

//返回狀態(tài)判斷(添加響應(yīng)攔截器)
Axios.interceptors.response.use(
    res => {
        //對(duì)響應(yīng)數(shù)據(jù)做些事
        if (res.data.errcode != 0) {
            return Promise.reject(res.data.errdesc);
        };
    },
    error => {
        return Promise.reject("返回?cái)r截報(bào)錯(cuò)信息"+error);
    }
);

// 對(duì)axios的實(shí)例重新封裝成一個(gè)plugin ,方便 Vue.use(xxxx)
export default {
    install: function (Vue, Option) {
        Object.defineProperty(Vue.prototype, "$http", { value: Axios });
    }
};
    

3.使用

this.$http.post('/goods/listGoods')
    .then(function(res){
        console.log(res);
    })
    .catch(function(error){
        console.log(error);
    });    

4.瀏覽器打印信息 返回?cái)r截報(bào)錯(cuò)信息TypeError: Cannot set property 'accessToken' of undefined 但localstorage里確實(shí)是存在的。
5.其他不需要tocken的接口沒(méi)問(wèn)題。

回答
編輯回答
亮瞎她

謝謝回答。我忽略了。

        config.data = {
            accessToken:JSON.parse(localStorage.getItem("joywareUser")).accessToken,
        }

應(yīng)該是這樣。直接config.data.accessToken 當(dāng)然是undefined。。。。

2017年8月7日 13:34
編輯回答
孤影

那是因?yàn)槟闱懊鎐onfig.data.accessToken這句報(bào)錯(cuò)的,你可以打印config.data看下,這時(shí)應(yīng)該已經(jīng)是undefined了。

2017年7月4日 12:49