从React客户端服务器访问在Django后端服务器上设置的cookie

问题描述

我的前端和后端解耦,客户端在localhost:3000上运行,后端在localhost:8000上运行。我有csrf和刷新令牌,并且在服务器端将它们设置为cookie。现在,我需要在客户端使用这些cookie。 这是我写的React代码

fetch('http://localhost:8000/api/Acutes/SignIn/',{
      method: 'POST',headers: {
      'Content-Type': 'application/json','withCredentials': 'true'
       },body: JSON.stringify(values)
       })
       .then(data => data.json())
       .then(data =>{
             console.log(data)
         })
       .catch(error =>{
         console.error(error);
         })

Django设置

CORS_ORIGIN_WHITELIST = [
    "http://localhost:9001","http://localhost:3000"
]

CORS_ALLOW_HEADERS = [
    'accept','accept-encoding','authorization','content-type','dnt','origin','user-agent','x-csrftoken','x-requested-with','withCredentials'
]

使用此方法时似乎出现的错误如下。

Access to fetch at 'http://localhost:8000/api/Acutes/SignIn/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field withcredentials is not allowed by Access-Control-Allow-Headers in preflight response.

我应该如何处理此错误并将cookie放入客户端?TIA

解决方法

我遇到了类似的问题,为了摆脱它,我进行了以下更改- 使用 - pip install django-cors-headers 将 django-cors-headers 包添加到您的项目中 将以下内容添加到 settings.py -

CORS_ORIGIN_WHITELIST = ['http://localhost:3000']

CORS_ALLOW_CREDENTIALS = True

CORS_ORIGIN_ALLOW_ALL=True

CSRF_TRUSTED_ORIGINS = ['http://localhost:3000']

MIDDLEWARE = [
           'corsheaders.middleware.CorsMiddleware',....
              ]

INSTALLED_APPS = [
               ....
             'corsheaders',.....
                ]

为了获得 csrf 令牌,我添加了一个单独的 api-

from django.middleware.csrf import get_token
def csrf(request):
return JsonResponse({'csrfToken': get_token(request)})

现在在JS代码中你可以得到csrf令牌值如下-

async function getCsrfToken() {
  var csrfToken=getCookie('csrftoken');
  if (csrfToken === null) {
    const response = await fetch(`${API_HOST}/csrf/`,{
      credentials: 'include',});
    const data = await response.json();
    csrfToken = data.csrfToken;
  }
  document.cookie = "csrfToken="+csrfToken;
};

希望这能解决您的问题

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...