允许Nginx上的CORS使用AngularJS HTTP GET [英] Allow CORS on Nginx to work with AngularJS HTTP GET

查看:162
本文介绍了允许Nginx上的CORS使用AngularJS HTTP GET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在我的控制台中收到此错误

I kept getting this error in my console


XMLHttpRequest无法加载
http://d.biossusa.com/api/distributor?key= ****。请求的
资源上没有
'Access-Control-Allow-Origin'标头。因此不允许原点'null'访问。

XMLHttpRequest cannot load http://d.biossusa.com/api/distributor?key=****. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

我知道我有 CORS 问题,请不要不要告诉我。

I know that I have CORS issue, please don't tell me that.

我正在尝试修复它。请看我的步骤

I am trying to fix it. Please see my steps

添加我前端的配置。

<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">

  <p>Today's welcome message is:</p>
  <h1>{{myData}}</h1>

</div>

<script>

  var app = angular.module('myApp', []);

  app.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
  }

  ]);

  app.controller('myCtrl', function($scope, $http) {
    $http.get("http://d.biossusa.com/api/distributor?key=****")
    .then(function(response) {
        $scope.myWelcome = response.data;
    });
});


</script>






我试过



在我的后端服务端添加配置在我的Nginx配置上。


I've tried

adding the config on my back-end service side on my Nginx Configs.

我在Nginx网站上发现此链接= https ://enable-cors.org/server_nginx.html

I found this link on Nginx site = https://enable-cors.org/server_nginx.html

我在我的nginx配置中添加了这样的内容。

I've add that in my nginx config like this.

server {

    listen 80;
    server_name d.biossusa.com;
    root /home/forge/d.biossusa.com/distributor-application/laravel/public;

    # Enable this line for debugging to see which php.ini get use ... $php --ini
    # root /home/forge/d.biossusa.com/public;


    # FORGE SSL (DO NOT REMOVE!)
    # ssl_certificate;
    # ssl_certificate_key;

    index index.html index.htm index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;

        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*';
            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-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
            #
            # 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-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,Content-Range,Range';
            add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
         }


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


    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log off;
    error_log  /var/log/nginx/d.biossusa.com-error.log error;

    error_page 404 /index.php;

    location ~ \.php$ {

        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_read_timeout 600;
       fastcgi_send_timeout 600;
       fastcgi_buffers 16 16k;
       fastcgi_buffer_size 32k;
        fastcgi_index index.php;
        include fastcgi_params;

    }

    location ~ /\.ht {
        deny all;
    }

}






我不知道还有什么,我真的可以做到摆脱这个错误。


I don't know what else, I could really do to get rid of this error.

我们非常感谢任何提示或指示!!!

Any hints or directions on this will be much appreciated !!!

根据@Yaser答案更新Nginx设置

server {

    listen 80;
    server_name d.biossusa.com;
    root /home/forge/d.biossusa.com/distributor-application/laravel/public;

    index index.html index.htm index.php;

    charset utf-8;

    location / {
       set $cors '';
       if ($http_origin ~ '^http?://(www\.d.biossusa\.com)') {
               set $cors 'true';
       }

       if ($cors = 'true') {
               add_header 'Access-Control-Allow-Origin' "$http_origin" always;
               add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
       }
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log off;
    error_log  /var/log/nginx/d.biossusa.com-error.log error;

    error_page 404 /index.php;

    location ~ \.php$ {

        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_read_timeout 600;
       fastcgi_send_timeout 600;
       fastcgi_buffers 16 16k;
       fastcgi_buffer_size 32k;
        fastcgi_index index.php;
        include fastcgi_params;

    }

    location ~ /\.ht {
        deny all;
    }

}

结果:

XMLHttpRequest无法加载http://d.biossusa.com/api/distributor?key=****。请求的资源上不存在Access-Control-Allow-Origin标头。因此不允许原点'null'访问。响应的HTTP状态代码为404.

server {

    listen 80;
    server_name d.biossusa.com;
    root /home/forge/d.biossusa.com/distributor-application/laravel/public;

    index index.html index.htm index.php;

    charset utf-8;

    location / {

       try_files $uri $uri/ /index.php?$query_string;

       set $cors '';
       if ($http_origin ~ '^http?://(www\.d.biossusa\.com)') {
               set $cors 'true';
       }

       if ($cors = 'true') {
               add_header 'Access-Control-Allow-Origin' "$http_origin" always;
               add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
       }
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log off;
    error_log  /var/log/nginx/d.biossusa.com-error.log error;

    error_page 404 /index.php;

    location ~ \.php$ {

        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_read_timeout 600;
       fastcgi_send_timeout 600;
       fastcgi_buffers 16 16k;
       fastcgi_buffer_size 32k;
        fastcgi_index index.php;
        include fastcgi_params;

    }

    location ~ /\.ht {
        deny all;
    }

}

结果

** XMLHttpRequest无法加载http://d.biossusa.com/api/distributor?key=****。请求的资源上不存在Access-Control-Allow-Origin标头。因此不允许原点'null'访问。**

推荐答案

首先你可以'从Angular或一般在客户端分配CORS权限。

First of all you can't assign CORS permission from Angular, or generally on client side.

然后您不必为每个请求类型重复该行,只需将其放在根目录中即可。你的配置文件:

Then you don't have to repeat that line for every request type, simply put it the in root of your config file:

server {


    listen 8080;

    location / {

        if ($http_origin ~* (http:\/\/d\.biossusa\.com\S*)$) {
            set $cors "true";
        }

        if ($request_method = 'OPTIONS') {
            set $cors "${cors}options";
        }

        if ($request_method = 'GET') {
            set $cors "${cors}get";
        }
        if ($request_method = 'POST') {
            set $cors "${cors}post";
        }

        if ($cors = "trueget") {
            add_header 'Access-Control-Allow-Origin' "$http_origin";
            add_header 'Access-Control-Allow-Credentials' 'true';
        }

        if ($cors = "truepost") {
            add_header 'Access-Control-Allow-Origin' "$http_origin";
            add_header 'Access-Control-Allow-Credentials' 'true';
        }

        if ($cors = "trueoptions") {
            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' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since';
            add_header 'Content-Length' 0;
            add_header 'Content-Type' 'text/plain charset=UTF-8';
            return 204;
        }
    }
}

这篇关于允许Nginx上的CORS使用AngularJS HTTP GET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆