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

CORS issue with Django and React hosted on same server

我在同一台服务器上使用 Django Rest Framework 和 React 应用程序时遇到 CORS 问题。我是 运行 Vagrant,安装了 Ubuntu 18 box 和 NGINX(我假设这个问题将转化为 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',)

反应 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

proxy pass 使用 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 进行了测试,一切都return按预期进行,所以我知道 DRF 正在正常工作。

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

最终更新

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

所以,我确实放弃了 django-cors-headers 并推出了自己的产品。为了回答 paulsm4 的问题,我在 NGINX 文件中没有 add_header 'Access-Control-Allow-Origin' '*';,尽管我确实考虑过让 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 从来没有使这两个包足够远以获得响应 headers 和任何类型的错误。使用我编写的中间件,fetch 能够完全调用,并且 return 一些响应 headers 无论是成功还是失败。

为了将来参考,我可能会重新访问 NGINX 并允许它处理 CORS。这里有一个很好的link CORS on NGINX

注意

澄清;除了 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 settings.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'
)

反应 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。

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

问题:您有一个 Django back-end 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 流量中的请求 headers 清楚地表明这还没有发生。

一些相关链接包括:

建议的下一步:

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