![Nginx 代理服务器的 CORS 问题?](https://linux22.com/image/786649/Nginx%20%E4%BB%A3%E7%90%86%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%9A%84%20CORS%20%E9%97%AE%E9%A2%98%EF%BC%9F.png)
我正在尝试调用端口 80 上的 docker 容器上的 API。我已经设置了 Nginx 代理服务器。
如果我通过 postman 访问,它可以工作,所以我假设代理服务器设置正确。
当我尝试通过 angular/$http 访问时,我得到了可怕的信息:来自原点‘http://localhost:8080’的对‘http://mydomain:8099/api/v4/documents’处的 XMLHttpRequest 的访问已被 CORS 策略阻止:在预检响应中,请求标头字段 x-session-token 不被 Access-Control-Allow-Headers 允许。
这是我的 Nginx 默认配置文件:
server {
listen 8099 default_server;
listen [::]:8099 default_server;
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
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-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
proxy_pass http://127.0.0.1;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
}
}
谢谢你的帮助