angular2 nginx Access-Control-Allow-Origin

时间:2017-04-19 12:21:12

标签: angular nginx cors

为了正确理解我目前面临的问题,我需要解释用例。

我有一个用Qt编写的桌面应用程序,它带有一个webserver模块,用于创建本地网络可访问的HTTP服务器。另一方面,在正常(连接到互联网)nginx服务器上托管了一个Angular2应用程序。

Angular2应用程序应该充当桌面应用程序的远程控制。

启动远程应用程序(angular)时,它向localhost发送一个请求,要求显示某些UI元素的json文件

但是,如果我禁用了我的CORS Chrome插件,则应用程序将失败并显示以下错误:

XMLHttpRequest cannot load http://192.168.178.22:8080/preset. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.webserver.com' is therefore not allowed access.

通常情况下我不会介意启用插件,但应用程序的主要目标是移动设备。

为了解决这个问题(所以我认为),我将CORS Headers添加到我的nginx配置中,方法如下:

# vhost
# www.webserver.com
server {
    listen 80;
    listen [::]:80;

    server_name www.webserver.com;

    charset utf-8;

    root /var/www/www.webserver.com/html;
    index index.html;

    location / {

        if ($request_method = 'OPTIONS') {

            add_header 'Access-Control-Allow-Origin' '*';

            # apparently for cookies
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';

            # Custom headers and headers various browsers *should* be OK with but aren't
            add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

            # Tell client that this pre-flight info is valid for 20 days
            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' '*';
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
         }

         if ($request_method = 'GET') {
            add_header 'Access-Control-Allow-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-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
         }

        # do the path matching stuff
        try_files $uri $uri/ /index.html;
    }

}

即使在那之后我得到了同样的错误,我是否在服务器方面错过了什么?错误可能在本地服务器端(Qt)吗?

我真的不再有想法了。

0 个答案:

没有答案