Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nginx反向代理跨域请求头options问题 #14

Open
zuobaiquan opened this issue Nov 18, 2020 · 0 comments
Open

nginx反向代理跨域请求头options问题 #14

zuobaiquan opened this issue Nov 18, 2020 · 0 comments

Comments

@zuobaiquan
Copy link
Owner

zuobaiquan commented Nov 18, 2020

在项目中遇到一个问题,axios跨域请求的时候会先发一个options请求来验证可以使用的请求头,然后再发送真证的请求,服务器是使用的php开的的。。响应的options的请求代码如下

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Authorization,Access-Token, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE');
header("HTTP/1.0 200 OK");
exit(0);
}

直接返回头信息,不用输出内容。然后本地测试的时候就可以啦。。。于是上线到服务器使用,但是出问题啦。options这个请求老是报错也没有看到响应的上面设置的头信息,于是就调试输出看 $_SERVER['REQUEST_METHOD'] 到底输出什么东西,options请求服务器居然输出啦 GET 请求 ,然后才想到服务器里用啦 nginx 反向代理,

解决方法
在nginx中设置options的响应请求,配置如下

server {
listen 80;
server_name www.aaaaa.com;
location / {
if ( $request_method = 'OPTIONS' ) {
add_header Access-Control-Allow-Origin $http_origin;
add_header Access-Control-Allow-Headers Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Data-Type,X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS,HEAD,PUT;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Headers X-Data-Type,X-Auth-Token;
return 200;
}
proxy_pass http://www.bbbi.com:8080;
index index.html index.php index.htm;
}
}

注意事项

跨域请求的时候options请求可以直接返回对应的跨域头后就结束脚本,当第二次请求真正的数据get/post请求返回时邮样要设置跨域的请求头,不然还会报错

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant