【问题标题】:Nginx. Blocked by CORS policyNginx。被 CORS 政策阻止
【发布时间】:2020-06-29 23:59:34
【问题描述】:

当前 nginx 配置:

server {
    listen hidden:80;
    server_name dev.hidden.com;
    root /var/www/back/hidden-api;


    location / {
        add_header 'Access-Control-Allow-Origin' "$http_origin" always;
        add_header 'Access-Control-Allow-Credentials' 'true' always;
        add_header 'Access-Control-Allow-Headers' "Origin, X-Requested-With, Content-Type, Accept" always;

        proxy_pass http://localhost:8081;
        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

}

那只是没有尝试,但错误仍然如下:

Access to XMLHttpRequest at 'http://dev.hidden.com/usr/register/do' from origin 'http://front.hidden.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

【问题讨论】:

    标签: nginx cors


    【解决方案1】:

    您能否尝试将以下内容添加到位置块内的配置中:

    if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' "$http_origin" always;
            add_header 'Access-Control-Allow-Credentials' 'true' always;
            add_header 'Access-Control-Allow-Headers' "Origin, X-Requested-With, Content-Type, Accept" always;
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain; charset=utf-8';
            add_header 'Content-Length' 0;
            return 204;
         }
    

    有关 CORS 预检检查的更多信息,请参阅 https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Preflighted_requests

    【讨论】:

    • 别忘了添加所有需要的 Access-Control-Allow-Headers
    猜你喜欢
    • 2018-03-22
    • 2020-07-29
    • 2021-09-17
    • 2021-06-13
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    相关资源
    最近更新 更多