2017-11-10 127 views
0

我有兩個nginx服務器通過docker在本地主機上運行。我想要一個服務器通過ajax調用另一個(api)並作出反應。我得到了這一切工作的在一個點,但我又解僱了我的服務器和我得到:兩個NGINX服務器通過CORS問題

無法加載http://localhost:8081/items?Title=butterflies:沒有 「訪問控制允許來源」標頭出現在請求 資源。 'http://localhost:8080'因此不允許 訪問。

因此Cors問題已經返回。我在我的default.conf下面的代碼:

server { 
    listen 8080; 

    root /app/public; 
    index index.php index.html; 
    charset utf-8; 

    access_log /var/log/nginx/access.log; 
    error_log /var/log/nginx/error.log; 

    error_page 404 = /handle404.php; 

    location/{ 
     try_files $uri $uri/ /index.php?$args; 
     add_header "Access-Control-Allow-Origin" "*" always; 
     add_header "Access-Control-Allow-Methods" "POST, GET, OPTIONS" always; 
    } 

    # Docker image version endpoints 
    location /version { 
     default_type text/plain; 
     rewrite ^/version/bisapi-php$ /version/bisapi-php.php last; 
    } 

    location ~ \.php$ { 
     include fastcgi_params; 
     fastcgi_pass php:9000; 
     fastcgi_read_timeout 900; 
     fastcgi_index index.php; 
     fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 
    } 

而且,這裏是我的代碼,我調用的API反應:

var encodedURI = window.encodeURI('http://localhost:8081/items?Title=butterflies', { crossdomain: true }); 
    return axios.get(encodedURI).then(function(response){ 
     return response.data; 
    }); 

所以我顯然有我的根內的普遍要求我的網站。不知道爲什麼它不會允許這個。我在nginx領域處於一片新生境,所以請大家幫忙。

+1

您需要在8081服務器上添加Access-Control-Allow-Origin和Access-Control-Allow-Methods標頭。它們在8080服務器上不是必需的,因爲這是前端代碼運行的地方。因此,您的前端代碼發送跨源請求的服務器需要在其響應中返回這些標頭。 – sideshowbarker

+0

是的,這是當前正在運行我的default.conf的服務器,上面的代碼包括Access-Control-Allow-Origin和Access-Control-Allow-Methods。仍然不起作用。 – tcoulson

回答

0

我將我的標題移出位置\,並將它們放在服務器標記內,以便全局調用標題並使其工作。我一定是在不同的路上。