如何使用React存储API身份验证令牌?

时间:2020-05-20 03:07:54

标签: reactjs authentication

我正在尝试从我的API存储一个身份验证令牌,因此我可以使用它向另一个API发出GET请求,我的代码如下:

fetch('APIURL', {
        method: 'POST',
        body: JSON.stringify({
            username: currentUser.username,
            password: currentUser.password,
        }),
    })
        .then(response => console.log(response))
        .then(json => console.log(json))

用户名和密码来自我的表单输入,我已经成功发出了POST请求,并在浏览器中获得了令牌,但是我想将其存储在代码中,在此先感谢:)

2 个答案:

答案 0 :(得分:0)

您可以使用localstorage设置并获取身份验证令牌。

要在本地存储中保存字符串,可以使用

window.localStorage.setItem(key, value);

您可以稍后通过以下方式获取值:

window.localStorage.getItem(key);

答案 1 :(得分:0)

对于任何想知道的人,我都使用带有以下代码的axios使其起作用:

axios({
        method: "post",
        url: "APIURL",
        data: {
            username: currentUser.username,
            password: currentUser.password
        }
    })
        .then(function (response) {
            const responseStatus = (response.status)
            const authToken = (response.data)

        })

仍然感谢您的帮助!

相关问题