簡體   English   中英

使用全局 axios 配置未定義不記名令牌

[英]bearer token undefined with global axios config

我使用 Axios 創建了一個 Vue 應用程序。 我通過 Vue UI 依賴安裝安裝了 Axios。 在我的main.js文件中,我添加了一個全局配置

import Vue from "vue";
import "./plugins/vuetify";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import axios from "axios";

Vue.config.productionTip = false;

axios.defaults.baseURL = "http://localhost:3000";
axios.defaults.headers.common["Authorization"] = `Bearer ${localStorage.token}`;
axios.defaults.headers.post["Content-Type"] = "application/json";

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");

當我想signOut我執行此操作

signOut: async function() {
  try {
    const response = await axios.post("/users/signout");
    // go on
  } catch (err) {
    // err handling
  }
}

但帖子標頭返回一個未定義的令牌Bearer undefined 所以我刪除了這一行

axios.defaults.headers.common["Authorization"] = `Bearer ${localStorage.token}`;

來自main.js文件並使用此代碼

signOut: async function() {
  try {
    const request = axios.create({
      baseURL: "http://localhost:3000/users/signout"
    });
    request.defaults.headers.common['Authorization'] = `Bearer ${localStorage.token}`;
    const response = await request.post();
    // go on
  } catch (err) {
    // err handling
  }
}

這很好用。 Authorization標頭設置正確。 為什么現在有效? 我該如何解決第一種方法?

由於您在main.js中設置授權標頭,它將在應用程序啟動時執行一次。 如果在您的localStorage該令牌不存在,它將是undefined並且將保持這種狀態,直到請求擁有它自己的令牌。 現在,在第二種方法中,您的令牌存在於localStorage ,因此它將正確設置標頭。

在您的第一種方法中,您可以通過刪除該Authorization標頭分配並直接在您的請求中分配令牌來解決此問題,或者創建一個函數,該函數將在服務器中的令牌發生更改(或被刪除)時分配默認標頭身份驗證。

更新:使用重定向攔截器的更清晰示例

axios.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');
    const auth = token ? `Bearer ${token}` : '';
    config.headers.common['Authorization'] = auth;
    return config;
  },
  error => Promise.reject(error),
);

這樣,在每個請求之前,我們的令牌將從 localStorage 中重新讀取,並且更新后的 Bearer 令牌將在標頭中設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM