【问题标题】:Error when reactjs requests from Django server (403 error / CORS)来自 Django 服务器的 reactjs 请求时出错(403 错误/CORS)
【发布时间】:2021-11-26 04:31:10
【问题描述】:

我有一个 reactjs 项目,它使用 API 向 django-rest-framework 发出请求。 它之前工作正常,但我不确定是什么导致它停止工作。

我已经在使用 django-cors-headers。

我的设置.py:

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

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]

CORS_ALLOW_ALL_ORIGINS = True

我的 reactjs 请求:

fetch('/api/user/', {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(obj)
})

我在 django 终端中遇到的错误:

Forbidden: /api/user/
[06/Oct/2021 01:15:31] "POST /api/user/ HTTP/1.1" 403 58

reactjs 浏览器中的控制台和网络选项卡出错:

// console error:
UserPage.js:65 POST http://localhost:3000/api/user/ 403 (Forbidden)

//network error:
Referrer Policy: strict-origin-when-cross-origin

//Preview in Networks tab:
detail: "CSRF Failed: CSRF token missing or incorrect."

更新 我的 reactjs 终端:

Local:            http://localhost:3000
On Your Network:  http://172.22.192.1:3000

当我使用 http://172.22.192.1:3000 打开我的 react 项目时,它工作正常,但使用 http://localhost:3000 它仍然无法发送 POST 请求。

【问题讨论】:

  • 我不知道为什么有些人反对,如果我遗漏了什么,请告诉我,以便我可以添加。

标签: reactjs django django-rest-framework cors django-cors-headers


【解决方案1】:

要解决您的问题,您可以在 Django 设置文件中使用 CORS_ORIGIN_WHITELIST 而不是 CORS_ALLOW_ALL_ORIGINS

替换:

CORS_ALLOW_ALL_ORIGINS = True

作者:

CORS_ORIGIN_WHITELIST = (
    'http://localhost:3000',  # React default port = 3000
    'http://localhost:8000',  # Django default port = 8000
)
# Change the url to suit your needs.

NB : CORS_ALLOW_ALL_ORIGINS 定义为 True 必须允许所有来源,但我之前遇到过同样的问题并用 CORS_ORIGIN_WHITELIST 替换它解决了它。那就试试吧。

Django CSRF-TOKEN 更新: This link may solve your issue about csrf_token

【讨论】:

  • 试过了,但没有成功。
  • 我在networks选项卡中添加了一个新错误,这是否意味着我应该添加一个令牌?
  • 您在使用SessionAuthentication 吗?在你的 api 上?
  • 我不这么认为,我确实有一个超级用户,但是在请求时我不需要任何登录或身份验证。
  • 当我使用这个打开浏览器时:172.22.192.1:3000,它起作用了。但仍然无法使用:localhost:3000
猜你喜欢
  • 2015-06-15
  • 1970-01-01
  • 2019-01-30
  • 1970-01-01
  • 2017-02-10
  • 1970-01-01
  • 2021-07-12
  • 1970-01-01
  • 2021-07-27
相关资源
最近更新 更多