如何存储JWT以及如何在Cookie中使用它

时间:2018-10-14 00:48:02

标签: javascript django reactjs cookies jwt

我有一个Django REST后端和React前端。我的提交功能如下:

handleSubmit = async event => {
    event.preventDefault();
    const { username, password } = this.state;
    const response = await login(username, password);
    console.log(response.data.token);
};

response.data.token成功返回,但我的问题是:

如何存储它以便在另一个HTTP请求中使用? (使用Cookie解决方案)

1 个答案:

答案 0 :(得分:0)

我找到了universal-cookie

的解决方案

我的最终代码是:

import Cookies from "universal-cookie";
const cookies = new Cookies();

...

handleSubmit = async event => {
   event.preventDefault();
   const { username, password } = this.state;
   const response = await login(username, password);
   cookies.set("access_token", response.data.token);
};