【问题标题】:Accessing cookies set at django backend server from the React client server从 React 客户端服务器访问在 django 后端服务器设置的 cookie
【发布时间】:2020-08-23 11:36:03
【问题描述】:

我的前端和后端是分离的,客户端在localhost:3000 上运行,后端在localhost:8000 上运行。我有 csrf 和刷新令牌,我将它们设置为服务器端的 cookie。现在我需要客户端的那些 cookie。 这是我写的反应代码:

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.

我应该如何处理这个错误并将我的cookies放到客户端?TIA

【问题讨论】:

  • 你需要更新它的后端
  • @ShubhamVerma 我在后端添加了“withCredentials”,但只有 csrf 令牌在 cookie 中可用,即使没有任何令牌是 HTTPonly
  • 它的 cors 问题。我对django一无所知。基本上你需要允许本地主机或不同的端口。它不是前端问题
  • 你检查过这个问题吗? stackoverflow.com/questions/32500073/…您可以尝试删除 withCredentials 标头字段以查看是否允许基本请求。
  • CORS_ORIGIN_ALLOW_ALL = True 替换CORS_ORIGIN_WHITELIST = [...] 并让我们知道行为。谢谢。

标签: django reactjs cookies decoupling csrf-token


【解决方案1】:

我遇到了类似的问题,为了摆脱它,我做了以下更改- 使用 -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;
};

希望能解决你的问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-24
    • 2021-11-02
    • 2019-11-26
    • 2020-01-16
    • 1970-01-01
    • 2016-11-16
    • 2012-12-07
    • 1970-01-01
    相关资源
    最近更新 更多