Django 和 React 托管在同一台服务器上的 CORS 问题

IT技术 django reactjs nginx cors vagrant
2021-05-25 06:42:58

我的 Django Rest Framework 和 React 应用程序在同一台服务器上存在 CORS 问题。我正在运行带有 Ubuntu 18 机器和 NGINX 的 Vagrant(我假设这个问题将转化为 DigitalOcean)如果我提供了太多信息,我提前道歉。DRF 使用 Supervisor,Gunicorn 使用端口 8000。我使用 create-react-app 创建了我的 React 应用程序。然后我用来npm run build创建静态文件。

NGINX 设置:

react会议

server {
    listen 8080;
    server_name sandbox.dev;

    root /var/sites/sandbox/frontend/build;
    index index.html;
    client_max_body_size 4G;
    location / {
        try_files $uri $uri/ /index.html;
    }

Django会议

upstream sandbox_server {
    server unix:/var/tmp/gunicorn_sanbox.sock fail_timeout=0;
}
server {
    listen 8000;
    server_name api.sandbox.dev;
    ...
    location / {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    if (!-f $request_filename) {
        proxy_pass http://sandbox_server;
        break;
    }

Django 设置:

INSTALLED_APPS = [
    ...
    'rest_framework',
    'corsheaders',
    'myapp',
]
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    ...
]

我尝试了以下但没有运气

CORS_ORIGIN_ALLOW_ALL = True

CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = ('192.168.19.76:8080','localhost:8080',)

react App.js

...
fetch("http://localhost:8000/api/v1/token-auth/", {
    method: 'POST',
    headers: {
       'Content-Type': 'application/json',
    },
    body: JSON.stringify({"email":"test@user.com", "password":"testuser"}),
})

因此,声明明显的 CORS 是正确的,因为 Origin 是 localhost:8080,这是一个不同的端口,因此它将其视为跨源。我已经尝试了使用 cors origin allow 的不同设置,但每次仍然是同样的问题。显然我做错了什么,但我看不到。

我的想法是

选项1

代理传递使用 django nginx conf 文件并取消 react nginx conf 文件,但我不知道这可能会对生产造成什么影响,或者这是否是一个好主意。有没有更好的办法?

location /api {
    proxy_set_header X-Forwarded_for $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://sandbox_server;

所以最后确定我的想法和我的问题。在为 CORS 尝试了不同的 Django 选项后,我仍然收到 CORS 错误。为什么,是我的 NGINX conf 文件导致它还是其他原因?我会希望在 DigitalOcean 中看到这个吗?

更新 1

我忘了添加错误。这是 CORS 错误

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/v1/token-auth/. (Reason: CORS request did not succeed).

对于那些想知道网络选项卡输出的人

Host    localhost:8000
Origin  http://192.168.19.76:8080
Pragma  no-cache
Referer http://192.168.19.76:8080/

更新 2 我使用 curl 进行了测试,一切都按预期返回,所以我知道 DRF 工作正常。

curl --data "email=test@user.com&password=testuser" http://localhost:8000/api/v1/token-auth/

最后更新

感谢 paulsm4 的所有帮助和非常棒的。

所以,我确实放弃了 django-cors-headers 并推出了自己的。为了回答 paulsm4 的问题,我add_header 'Access-Control-Allow-Origin' '*';在 NGINX 文件中没有,虽然我确实考虑过让 NGINX 处理 CORS 与 Django,但从未走那么远。@paulsm4,这就是我所说的 proxy_pass。关键是将此代码块添加到 NGINX 以与我的中间件结合使用。

    location /api {
        proxy_set_header X-Forwarded_For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://sandbox_server;

上面的代码本身有效,但它不允许我将任何传入的 URL 列入白名单。创建我自己的中间件允许我加入白名单。我不知道为什么 django-cors-headers 甚至 django-cors-middleware 对我不起作用。奇怪的是,除了我询问的 CORS 错误之外,这两个包的 fetch 从未获得足够的响应头和任何类型的错误。使用我编写的中间件,fetch 能够完全进行调用,并且无论成功还是失败都返回一些响应标头。

为了将来参考,我可能会重新访问 NGINX 并允许它处理 CORS。这是NGINX 上的一个很好的CORS链接

笔记

澄清; 除了 Django 已经包含的中间件之外,唯一安装的中间件是 cors 中间件。Django 和 React 位于同一台服务器上,但端口不同。

  1. api.sandbox.com:8000 是 Django Rest 框架
  2. app.sandbox.com:8080 是 React 静态文件
  3. Django 2.0.2
  4. python 3.6
  5. django-cors-headers 2.4.0
  6. Vagrant/VirtualBox Ubuntu 18.04
  7. NGINX

Django设置.py

INSTALLED_APPS = [
    ...
    # Third Party
    'rest_framework',
    'corsheaders',
    # My Apps
    'account',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
    'django.middleware.csrf.CsrfViewMiddleware',
    'corsheaders.middleware.CorsPostCsrfMiddleware',
    ...
]
CORS_ORIGIN_WHITELIST = (
    'null',
    '192.168.19.76:8080',
    'localhost:8080',
    'app.sandbox.com:8080'
)

react App.js

    fetch("http://localhost:8000/api/v1/token-auth/", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            "email": "test@user.com", 
            "password": "testuser"
       }),
    })

所以我在这里不知所措。它要么是 django-cors-headers 不起作用,要么可能是 NGINX。

1个回答

我们一直在交换意见;这是我目前的理解:

问题:您有一个 Django 后端 API(在端口 8080)和一个 React 前端(在端口 8000)。两者目前都在本地主机上运行,​​但最终将驻留在 DigitalOcean 上。React 客户端正在获取Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/v1/token-auth/. (Reason: CORS request did not succeed).

您需要配置 CORS。

您捕获的 HTTP 流量中的请求标头清楚地表明这还没有发生。

一些相关链接包括:

建议的下一步:

如果您还没有,请安装和配置django-cors-headers