CORS,nginx via vagrant,以及来自browsersync的站点

时间:2017-10-27 20:22:12

标签: javascript php ajax nginx cors

不确定我做错了什么,但我无法通过浏览器同步获取我的静态html网站,以便从我正在建设的另一个网站提取数据。

因此,我在server { listen 80; listen 443 ssl; server_name example.loc ~^example\.\d+\.\d+\.\d+\.\d+\.xip\.io$; # Tells nginx which directory the files for this domain are located root /srv/www/example/htdocs/current; rewrite ^/(.*)/$ /$1 permanent; location /api/api.php { if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' $http_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' $http_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' $http_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'; } ... } ... } 处提供了我的静态网站,试图从var url ='http://example.loc/api/api.php?querystuff' var xhr = new XMLHttpRequest(); if (!('withCredentials' in xhr)) xhr = new XDomainRequest(); // fix IE8/9 xhr.open('GET', url); xhr.onload = success; xhr.send(); 获取一些JSON数据。

该网站的我的nginx配置

{{1}}

我的静态网站正在点击端点:

{{1}}

这就是Chrome给我的回应:

  

无法加载   http://example.loc/api/api.php?api=line_status&line=red:不   请求中存在“Access-Control-Allow-Origin”标头   资源。因此不允许来源“http://127.0.0.1:4000”   访问。

我错过了什么?

1 个答案:

答案 0 :(得分:1)

经过一夜安眠之后,我意识到问题是什么,这是阻止秩序。我的nginx配置有另一个位置块,它以:

开头
read new_last
set -- "${@:1:$(( $# - 1 ))}" "$new_last"

这比我上面列出的位置块先例。我只是在我的位置块中添加了一个等号:

location ~ \.php {}

它现在有效。

对于遇到此问题的其他人,以下帮助我: