首页 > 解决方案 > Nginx 从源获取已被 CORS 策略阻止

问题描述

我在后端 API 的前面有 Nginx,具有以下配置并暴露于api.dev.example.com

    upstream api {
        server api:8000;
    }

    server {
        listen              80 default_server;
        server_name         localhost;

        location / {
            if ($request_method = OPTIONS) {
                return 204;
            }
            proxy_pass http://api;
            add_header Access-Control-Allow-Origin *;
            add_header Access-Control-Max-Age 3600;
            add_header Access-Control-Expose-Headers Content-Length;
            add_header Access-Control-Allow-Headers Range;
        }
    }

我在 ( localhost:3000) & 运行的本地前端开发环境中使用 API 端点,但是当 API 返回代码不是2xx

Access to fetch at 'https://api.dev.example.com/api/v1/users' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这个问题的任何解决方案?

标签: nginxnginx-reverse-proxynginx-config

解决方案


推荐阅读