2017-11-10 126 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

我将我的标题移出位置\,并将它们放在服务器标记内,以便全局调用标题并使其工作。我一定是在不同的路上。