我需要启用cors策略来到达我的API,我在我的nginx服务器文件上做了以下配置:
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name api.domain.com;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_pass http://my_ip:6869/;
set $ref "*";
if ($http_referer ~* ^(http?\:\/\/)(.*?)\/(.*)$) {
set $ref $1$2;
}
add_header 'Access-Control-Allow-Origin' $ref always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,signature,timestamp' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
}
listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/api.domain.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/api.domain.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
字符串
但我一直得到以下错误:
Access to fetch at 'https://api.domain.com/data/key?matches=^art(.*)' from origin 'http://localhost:3500' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values '*, http://localhost:3500', but only one is allowed. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
型
看起来add_header是在一个已经设置好的头文件之上添加的,但是我只有这个配置文件,看不到它可能来自哪里。
有没有办法弄清楚是什么设置了初始头cors策略,或者只是覆盖它而不是添加它?
先谢谢你了。
1条答案
按热度按时间xeufq47z1#
如果您没有正确设置CORS配置,就会发生这种情况。您可以使用名为Allow-Control-Allow-Origin的插件/扩展在本地计算机上修复此问题,并将您的本地主机添加到其中。
另一种方法是在服务器端手动修复配置。
如果您不熟悉CORS,它基本上用于允许某些跨域请求,同时拒绝其他请求。例如,如果站点提供可嵌入服务,则可能需要放宽某些限制。
更新
Nginx使用的是哪个编译器?如果是this,下面的代码必须修复它:
字符串