这是我当前的 nginx 配置文件:
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name _;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ /index.html;
}
location /home {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
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-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-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';
}
}}
我目前已将其设置好,因此它在服务器上按预期工作。从 index.html 引用文件时,文件可以正确显示,并且不存在 CORS 错误。
在本地 Web 服务器上进行开发时使用相同的 index.html(http://本地主机:4200)。
错误如下:
Access to Imported resource at 'http://sub.domain.io//public/bower_components/polymer/polymer.html' from origin 'http:/sub.domain.io' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
我已经尝试将“Access-Control-Allow-Origin *;”放入服务器{}中,而不是位置中。
你知道怎样完成这个吗?
答案1
也许,您在位置下指定的 URL 不是您尝试访问的位置。您的错误与路径有关http://sub.domain.io//public/bower_components/polymer/polymer.html
location /public
尝试添加 一个部分add_header 'Access-Control-Allow-Origin' '*';