鍍金池/ 問答/HTML/ axios攔截器攔截失敗

axios攔截器攔截失敗

我在做一個(gè)jwt認(rèn)證的功能.想要每次請求的時(shí)候帶上一個(gè)后臺(tái)傳回來的token.所以我在main.js里加了個(gè)攔截器.想在每一次請求的時(shí)候在header里帶上我的token.但是攔截器只在某一部分的請求.在某一些請求的header中加token.在有一些請求里又不能加token.我想問下怎么解決這個(gè)問題?我也嘗試了在單獨(dú)請求前設(shè)置header.依然沒效果.請各位大佬指點(diǎn)迷津

1.我在main.js里加了攔截器

clipboard.png

2.這是正??梢詳r截.已經(jīng)在頭上加上了token的請求

clipboard.png

3.但是在某些請求的時(shí)候就沒有token

clipboard.png

順便說一下.如果我把這個(gè)請求路徑換一下或者故意改成錯(cuò)的.他就能加到我的請求上.所以我在懷疑是不是同步異步的問題

第一次提問.感謝解惑

回答
編輯回答
心上人

1.建議封裝下
2.建議在api配置的時(shí)候加上參數(shù)用來決定是否在header中帶token

export const API = {
    login:{
        url: '////',
        method: 'post',
        token: true
    },
    ...
}
我們對請求做了封裝,可以傳一個(gè)api接口對象,在攔截器里在對最終對傳參序列化

3.可以把token存在緩存,判斷沒有時(shí)再去storage中取

2017年10月4日 09:28
編輯回答
硬扛

你看一下是不是token獲取的方式不行,這樣試試:

const token = localStorage.getItem("token");

保存的時(shí)候是使用localStorage.setItem("token",xxx)

2017年11月11日 12:34
編輯回答
舊時(shí)光

這得看代碼才能解決,基本上是代碼問題。建議將 axios 單獨(dú)封裝成 fetch() 并將配置統(tǒng)一在一個(gè)地方, 然后每次發(fā)的請求都走 fetch 確保都被攔截到

export default function fetch(options) {
    return new Promise((resolve, reject) => {
        const instance = axios.create({
            // 所有請求都會(huì)帶上這些配置
            headers: {
                'Content-Type': 'application/json'
            },
            timeout: 30 * 1000 // 30s 超時(shí)
        });

        // 發(fā)起請求時(shí),會(huì)執(zhí)行該方法
        instance.interceptors.request.use(options => {
            //...
            return options
        }, err => {
            return reject(err)
        })

        //接收到后臺(tái)的數(shù)據(jù)時(shí)執(zhí)行的方法
        instance.interceptors.response.use(response => response, err => resolve(err.response))

        instance(options)
            .then(response => { // 成功請求
                resolve(response)
            })
            .catch(error => { // 失敗請求
                console.error('請求異常:' + error)
                reject(error)
            })
    })
}
2017年11月11日 18:17