0

我正在尝试使用 Nginx 对 Django App + React 进行 dockerize,然后代理将请求与上游一起传递给我的后端。我遇到的问题是,如果我不启用 cors 并在我的后端允许 localhost:4000连接被拒绝。Nginx 抛出:

2021/09/02 21:57:02 [error] 26#26: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.21.0.1, server: , request: "GET /api/users/me HTTP/1.1", upstream: "http://172.21.0.4:8000/api/users/me", host: "localhost:4000", referrer: "http://localhost:4000/"

旁注:我不知道... client: 172.21.0.1 ... 上面的日志错误来自哪里。

我尝试将 ALLOWED_HOSTS 设置为["*"]["localhost", "localhost:4000", "127.0.0.1", "127.0.0.1:4000"] 但似乎问题不在这里。

使用 CORS:

CORS_ALLOWED_ORIGINS = [
    "http://localhost:4000",
    "http://127.0.0.1:4000",
] 

它工作得很好。

我没有尝试使用 cors 部署应用程序以在生产中对其进行测试

所以我的问题是:

  1. 这是允许流量通过我的网络服务器的正确方法吗?
  2. 如果可以在生产中使用 cors 是否可以?

这是我的 Nginx.conf:

upstream backend {
    server backend:8000;
}

server {
    listen 8080; #mapping port 4000:8080 from docker-compose
    error_log /var/log/nginx/api.error.log;

    location /api {
        proxy_set_header host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-forward-for $proxy_add_x_forwarded_for;
        proxy_pass http://backend;
    }

    location /staticbe/ {
        root /backend;
    }

    location /admin/ {
        proxy_set_header host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-forward-for $proxy_add_x_forwarded_for;
        proxy_pass http://backend;
    }

    location / {
        root   /var/www/react;
        index  index.html index.html;
        try_files $uri $uri/ /index.html;
    }

}

来自我的后端(达芙妮)的日志:

Starting server at tcp:port=8000:interface=127.0.0.1
HTTP/2 support not enabled (install the http2 and tls Twisted extras)
Configuring endpoint tcp:port=8000:interface=127.0.0.1
Listening on TCP address 127.0.0.1:8000

Gunicorn 和 Daphne 都有同样的问题

4

1 回答 1

-1

您需要在ALLOWED_HOSTS. 永远不要设置ALLOWED_HOSTS'*',因为这会将您的站点暴露给 HTTP Host 标头攻击。CORS 对于管理不同的来源非常有用且可靠,您可以在生产中使用它。

于 2021-09-03T02:00:32.173 回答