使用来自 localstorage 的 Bearer Token

Use Bearer Token from localstorage

所以我正在创建一个简单的 React Redux 应用程序,它使用 superagent 从数据库中获取一些元素并对它们进行一些操作。 我使用 Symfony 的 Api 平台作为后端并创建了一些 API。我的所有 API 都受到保护,需要持有者令牌才能访问它们。 我使用 JWT 创建了身份验证 API。

现在我正在尝试让数据显示在我的 React 应用程序中。我已经创建了一个正常运行的登录表单。我可以使用我的用户名和密码在 return 中获得一个令牌。

但我的问题是,在我进行身份验证并且应用程序将我重定向到我的主页(其中包含数据库中的元素列表)后,我的控制台出现错误

("{code: 401, message: "JWT Token not found"}
code: 401
message: "JWT Token not found")

这意味着我没有在我的请求中使用不记名令牌。

那么我如何在我的 POST、GET 和 PUT 请求中使用令牌,以便我可以使用它们。

PS: 我的令牌以名称 jwtToken 存储在我的本地存储中 这是我的 agent.js 文件:

import superagentPromise from 'superagent-promise';
import _superagent from 'superagent';

const superagent = superagentPromise(_superagent,global.Promise);
const API_ROOT='http://localhost:8000/api';
const responseBody = response => response.body;

let token =window.localStorage.getItem('jwtToken');;



const tokenPlugin = secured => {
    return (request) => {
        if (token && secured){
            request.set('Authorization',`Bearer ${token}`);
        }
};
};
export const requests={
    get: (url, secured = false)=>{
        return superagent.get(`${API_ROOT}${url}`).use(tokenPlugin(secured)).then(responseBody);
    },
    post: (url, body = null, secured = true) => {
        return superagent.post(`${API_ROOT}${url}`, body).use(tokenPlugin(secured)).then(responseBody);
    },
    setToken: (newJwtToken) => token = newJwtToken
    };

你的 get 接受 urlsecured 参数,也许你没有发送第二个参数,它默认为 false 并且 tokenPlugin 正在检查 token && secured

在您使用 get 的地方尝试 get(url, true)