不知道我在做什么错,但是我无法通过浏览器同步来获取我的静态html网站,从而无法从我正在从无业游民的网站中获取数据。
就像这样,我在127.0.0.1:4000
提供了我的静态站点,试图从example.loc/api/api.php?querystuff
获取一些JSON数据。
我对该网站的Nginx配置有
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();
这是Chrome给我的响应:
加载失败
http://example.loc/api/api.php?api=line_status&line=red:否
请求中存在“ Access-Control-Allow-Origin”标头
资源。因此,不允许来源'http://127.0.0.1:4000'
访问。
我想念什么?
最佳答案
经过一夜安眠后,我意识到问题出在哪里,这是顺序混乱。我的nginx配置有另一个以以下内容开头的位置块:
location ~ \.php {}
优先于我上面列出的位置块。我只是在位置块中添加了一个等号:
location = /api/api./php {}
现在就可以了。
对于其他遇到此问题的人,以下帮助我:
Nginx location priority
http://nginx.org/en/docs/http/ngx_http_core_module.html#location