如何在 axios 中配置授权承载令牌?

时间:2021-06-11 12:39:32

标签: javascript vue.js axios jwt vuex

嗨,我创建了一个登录操作(使用 Vuex),它将用户 jwt 令牌保存到本地存储。在此登录操作中,我调用另一个操作来获取该用户创建的一些帖子。当我在 fetchPosts 操作中的 get 请求的标头中传递令牌时,它完全正常工作。

async login(context, user){
    try {
       const res = await api.post('/users/login', user)
       localStorage.setItem('jwt', res.data.token)
       context.commit('SET_USER', res.data.user)
       context.dispatch('fetchPosts')
    }catch(err){
       console.log(err.response.data)
    }
}

async fetchPosts(context){
    try {
        const res = await api.get('/posts', {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('jwt')}`
          }
        })
        context.commit('SET_POSTS', res.data)
     }catch(err){
        console.log(err.response.data)
     }
}

上面的代码工作得很好,但问题是我有几个认证路由,我不想通过

headers: { Authorization: `Bearer ${localStorage.getItem('jwt')}`}

对于所有 api 请求。

我想在 1 个文件中进行配置,我尝试过,但是当我登录时,我收到未经身份验证的消息,当我检查网络选项卡时,我看到 Bearer null 已传递到授权中。请参阅下面我的配置尝试。

import axios from 'axios'
export default axios.create({
  baseURL: 'http://localhost:3000',
  headers: {
    Authorization: `Bearer ${localStorage.getItem('jwt')}`
  }
})

任何人都知道我哪里出错了或者我可以做些什么来解决这个问题。

2 个答案:

答案 0 :(得分:1)

这里有一个简单的例子说明如何做到这一点。

//No output produced by the code
#include <bits/stdc++.h>
using namespace std;

void removeElements(vector<int>& array, int start, int end)
{
    array.erase(array.begin() + start, array.begin() + start + end);
}

void processArray(std::vector<int>& array)
{
    int n = array.size();
    int count = 0;
    //for(auto e: array) cout << e << " ";
    for (int i = 0; i < n; i++) {
        int temp = i;
        while (i < n && array[i] >= 100) {
            count++;
            i++;
        }
        if (count >= 2) {
            array[temp] = count;
            removeElements(array, temp + 1, temp + count);
            i -= (count - 1);
        }
        count = 0;
    }
    for (auto e : array)
        cout << e << " ";

    //return array.size();
}

int main()
{
    std::vector<int> array;
    int val;
    while (std::cin >> val) {
        if (val < 0)
            break;
        array.push_back(val);
    }
    processArray(array);
    /* for(std::vector<int>::iterator a = array.begin(); a != array.end(); a++) {
                std::cout << *a << std::endl;
            }*/
    return 0;
}

查找更多信息here

答案 1 :(得分:0)

将此添加到您的 main.js 文件

    axios.interceptors.request.use(config => {
      const token = localStorage.getItem("jwt");
      config.headers["Authorization"] = `Bearer ${token}`;
      return config;
    });