[英]Reverse proxy CORS Configuration for NGINX
我有一个 nodejs 服务器和反应客户端应用程序部署到一个 ec2 实例。 当我尝试向 /api/emails 路由发送 POST 请求时,它会在控制台中返回 CORS / CORB 错误。
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:9001/api/email. (Reason: CORS request did not succeed).
我的应用服务器 nginx 配置如下所示:
server {
listen 80;
listen [::]:80;
server_name ec2-52-202-82-153.compute-1.amazonaws.com;
location / {
proxy_pass http://127.0.0.1:9001/;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
proxy_ssl_session_reuse off;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_set_header 'Access-Control-Allow-Origin' '*';
proxy_set_header 'Access-Control-Allow-Credentials' true;
}
}
我的应用程序客户端配置如下所示:
server {
listen 80;
listen [::]:80;
server_name ec2-52-202-82-153.compute-1.amazonaws.com;
location / {
proxy_pass http://127.0.0.1:9002;
}
}
通过https://enable-cors.org/server_nginx.html
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
如果你把它放在你的app-server
位置,它会看到它是一个飞行前请求,并立即返回一个 204。你必须使用所有不同的标头来获得你想要的。
请注意这确实假设您的nginx
配置设置正确,因为您有两个具有相同server_name
的服务器块
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.