尽管设置了标头,但 CORS 不起作用



我有一个应用程序,客户端通过https with nginx向example.com提出多部分请求,然后将文件上传到亚马逊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获取和发布请求工作。

问题是Nginx不接受大文件。将其放置在我的Nginx服务器配置的位置块中解决了我的问题:client_max_body_size 10M;

问题可能不是Nginx,因为它只是一个移动问题。尝试使用,而不是 *用于访问控制 - 允许原素,您也可以使用您的来源。

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());

最新更新