使用本地存储中的承载令牌

时间:2019-06-03 01:53:44

标签: reactjs api symfony react-redux superagent

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

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

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

("{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
    };

1 个答案:

答案 0 :(得分:2)

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

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

相关问题