簡體   English   中英

CORS,通過Vagrant的Nginx和網站通過browsersync提供

[英]CORS, nginx via vagrant, and sites serve from browsersync

不知道我在做什么錯,但是我無法通過瀏覽器同步來獲取我的靜態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 {}

現在就可以了。

對於其他遇到此問題的人,以下幫助我:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM