Access-Control-Allow-Origin 设置了还是报跨域错误?

司空慧丽 阅读 130

我在 Nginx 里配置了 Access-Control-Allow-Origin: *,前端调用接口时却还是报 CORS 错误,控制台提示“请求的资源上没有 ‘Access-Control-Allow-Origin’ 头”。明明配置了啊,是不是漏了什么?

这是我的 Nginx 配置片段:

location /api/ {
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
}
我来解答 赞 3 收藏
二维码
手机扫码查看
1 条解答
程序猿熙炫
这问题我遇到过好几次,Nginx配置看似没问题但其实有个坑。WordPress处理OPTIONS请求时会把Nginx的CORS头覆盖掉,特别是你用REST API的时候。

试试这样改Nginx配置:

location /api/ {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
}
}


如果还是不行,建议在WordPress里用钩子函数处理,更靠谱点:

add_action('init', function() {
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
exit;
}
});


记住要放在functions.php最前面,别被其他插件覆盖了。这种破事我调了无数次,每次都是被WordPress内部处理机制坑的。
点赞
2026-03-08 13:05