簡體   English   中英

盡管設置了標頭,但CORS不起作用

[英]CORS doesn't work despite headers set

我有一個應用程序,客戶端通過https與Nginx從example.com發出多部分請求到api.example.com,然后api將文件上傳到Amazon S3。

它適用於我的機器,但當其他人在不同的網絡上嘗試時它會中斷。 給我這個錯誤:

[Error] Origin https://example.com is not allowed by Access-Control-Allow-Origin.
[Error] Failed to load resource: Origin https://example.com is not allowed by Access-Control-Allow-Origin. (graphql, line 0)
[Error] Fetch API cannot load https://api.example.com/graphql. Origin https://example.com is not allowed by Access-Control-Allow-Origin.

我在API上使用cors npm包,如下所示:

app.use(cors());

所有這些都是通過DigitalOcean上的Nginx反向代理進行的。 這是我的Nginx配置:

個人服務器配置在/etc/nginx/conf.d/example.com.conf/etc/nginx/conf.d/api.example.com.conf ,幾乎相同,只是地址和名稱不同:

 server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        server_name example.com;

        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

        include snippets/ssl-params.conf;

        location / {
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-NginX-Proxy true;
            proxy_pass http://localhost:3000/;
            proxy_ssl_session_reuse off;
            proxy_set_header Host $http_host;
            proxy_cache_bypass $http_upgrade;
            proxy_redirect off;
        }
    }

當我在計算機上的localhost上使用它時它工作得非常好,但是當我把它放在DigitalOcean上時我無法上傳。 當我上傳文件時,它只在這個多部分請求中斷,其他常規的Cors GET和POST請求都有效。

問題是Nginx不接受大文件。 把它放在我的nginx服務器配置的位置塊中解決了我的問題: client_max_body_size 10M;

問題可能不在於nginx,因為它只是一個移動問題。 嘗試使用,而不是*用於Access-Control-Allow-Origin,您也可以使用您的原點。

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
    res.header("Authorization", "Access-Control-Allow-Headers", "Origin","X-Requested-With", "Content-Type", "Accept");
    next();
});

UPDATE

如果以上操作不起作用,請嘗試以下操作,這將暫時啟用所有內容。

app.use(cors());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM