Cookie 未存储在浏览器中

IT技术 reactjs django next.js
2021-05-03 00:35:52

使用Next.jsDjango Rest Framework,我正在使用 JWT 对用户进行身份验证。首先,当用户成功登录页面时,一个 cookie(包含 JWT 令牌)被发送到浏览器。当用户尝试访问特定页面时,此 cookie 用于验证请求。我在浏览器中存储 cookie 时遇到问题。

Django | 登录功能

@api_view(['POST'])
@permission_classes((permissions.AllowAny,))
def login(request):
 ...

response = Response()
response.set_cookie(key='jwt', value=token, httponly=True, max_age=86400)
response.data ={
    'message': 'success',
}
return response

这是我获取 /api/login 的方式

下一页 | 登录.js

        var axios = require('axios');
        var FormData = require('form-data');
        var data = new FormData();
        data.append('email', this.state.email);
        data.append('password', this.state.password);
        data.append('X-CSRFToken', csrftoken);
        data.append('mode', 'same-origin');
        data.append('Content-Type', 'application/json');

        
        var config = {
            method: 'post',
            credentials: 'include', #I'm probably having issues with this
            url: 'http://localhost:8000/api/login',
            data : data
        };

        axios(config)
        .then(res=> {
          console.log('success'); #I got logged, but cookie is not stored
        })
        .catch(
            error=>{this.setState({isError:true})}
        );

这是浏览器中的 set-cookie: 浏览器网络tap catpure 响应信息

JWT缺少存储: 浏览器中的存储选项卡

如您所见,在它们两个中,我都收到了名为 JWT 的 cookie。但它没有存储在浏览器中。提前感谢您的时间和答案!

1个回答

这是重要的要注意的是modecredentials不支持配置Axios。它在工作fetch api,因为这些选项的部分Request API(文档的模式都在这里)。

Axios底层使用XMLHttpRequest,而不是Request

试试这个

var axios = require('axios');
var FormData = require('form-data');
var data = new FormData();
data.append('email', this.state.email);
data.append('password', this.state.password);

const headers = {
  'Content-Type': 'application/json',
  'X-CSRFToken': csrfToken
}

var config = {
    method: 'post',
    withCredentials: true,
    url: 'http://localhost:8000/api/login',
    data : data,
    {headers: headers}
};

axios(config)
.then(res=> {
  console.log('success');
})
.catch(
    error=>{this.setState({isError:true})}
);

- - - - - - - - - - - - - - - 或者 - - - - - - - - - - ---------------

把它放在最上面

axios.defaults.withCredentials = true
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
axios.defaults.xsrfCookieName = "csrftoken";

这必须在 Django 中:

设置.py

CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
    'http://localhost:3000',
    'http://localhost:8000'
)