错误详情:

has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

错误缘由:

前端本地对接已上dev环境的接口域名,本地http请求https协议造成的跨域错误。从报错来看,浏览器的跨域预检请求 (OPTIONS 请求) 没有得到正确的响应。这通常是因为服务器没有返回 HTTP 200 OK 状态,或是预检请求的响应头不满足跨域策略的要求。

处理方法:

location /api/ {
    # 设置跨域头
    add_header 'Access-Control-Allow-Origin' '*' always;
    add_header 'Access-Control-Allow-Credentials' 'true' always;
    add_header 'Access-Control-Allow-Methods' 'POST, GET, PUT, OPTIONS, DELETE' always;
    add_header 'Access-Control-Allow-Headers' '*' always;

    # 处理 OPTIONS 请求
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'POST, GET, PUT, OPTIONS, DELETE';
        add_header 'Access-Control-Allow-Headers' '*';
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Length' 0;
        add_header 'Content-Type' 'text/plain; charset=utf-8';
        return 200;
        }

    # 转发其他请求到后端服务器
    proxy_pass https://your-backend-server;
}

上述配置中,当 OPTIONS 请求到达 /api/ 时,Nginx 会直接返回 200 状态,而不会转发到后端服务器。这可以有效避免预检请求失败的问题。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐