Nginx+PHP+Vue环境下CORS预检缺失Allow Origin Header错误排查
问题
使用Nginx+PHP+Vue架构开发时遇到CORS错误:正常Fetch请求可正常执行,但后端返回自定义业务错误(如注册时登录名已被占用)时,出现“Fetch failed”,开发者工具网络面板显示“CORS: Preflight Missing Allow Origin Header”错误。
当前Nginx配置:
server { listen 80 default_server; listen [::]:80 default_server; server_name _; server_tokens off; root /app/; index index.php; add_header "Access-Control-Allow-Origin" *; add_header "Access-Control-Allow-Headers" *; location / { try_files $uri $uri/ /index.php$is_args$args; } location ~ \.php$ { include fastcgi_params; fastcgi_pass php:9000; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } }
PHP返回错误的代码:
header("HTTP/1.0 460 Aplication Error"); header("Content-Type: application/json"); json_encode($error);
补充说明:通过Vue CLI Server发起Fetch请求时无法修改响应头,但直接在浏览器访问该接口时可正常返回。
解决方案
你的实现存在两处问题,对应修复方式如下:
1. Nginx的CORS头未覆盖错误响应
Nginx的add_header指令默认仅对2xx、3xx类成功响应生效,你返回的460属于自定义错误状态码,不会自动带上配置的CORS头,导致跨域校验失败。
修改Nginx配置,给add_header添加always参数,确保所有响应都携带CORS头:
add_header "Access-Control-Allow-Origin" * always; add_header "Access-Control-Allow-Headers" * always;
同时建议补充OPTIONS预检请求处理,复杂跨域请求会先发送OPTIONS请求,需明确返回允许的请求方法:
if ($request_method = OPTIONS) { add_header "Access-Control-Allow-Origin" * always; add_header "Access-Control-Allow-Headers" * always; add_header "Access-Control-Allow-Methods" "GET, POST, PUT, DELETE, OPTIONS" always; add_header "Content-Length" 0; add_header "Content-Type" "text/plain; charset=utf-8"; return 204; }
2. PHP错误返回代码的两处问题
- 状态码描述拼写错误:
Aplication应为Application json_encode($error)仅完成编码,未输出内容,需添加echo才能返回JSON响应
修正后的PHP代码:
header("HTTP/1.0 460 Application Error"); header("Content-Type: application/json"); echo json_encode($error);
内容的提问来源于stack exchange,提问作者Gutek
相关产品推荐
相关产品推荐

