Nginx - No' Access-Control-Allow-Origin'标头出现在请求的资源上。起源' null'因此不允许访问

时间:2017-02-06 14:23:27

标签: laravel nginx cors laravel-routing

我尝试对我的API后端进行GET并使用Angular打印数据

我的后端在

  • PHP Framework = Laravel
  • Web Server = Nginx

我有

AngularJS

<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配置(位置区块)

location / {

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

        set $cors '';
        if ($http_origin ~ '^https?://(localhost|www\.yourdomain\.com|www\.yourotherdomain\.com)') {
                set $cors 'true';
        }

        if ($cors = 'true') {
                add_header 'Access-Control-Allow-Origin' "$http_origin" always;
                add_header 'Access-Control-Allow-Credentials' 'true' always;
                add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
                add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;
                # required to be able to read Authorization header in frontend
                #add_header 'Access-Control-Expose-Headers' 'Authorization' always;
        }

        if ($request_method = 'OPTIONS') {
                # 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;
        }


    }

我曾经得到过CORS错误,我还没有得到它。

但我一直得到:

[![在此处输入图像说明] [1]] [1]

  

XMLHttpRequest无法加载http://d.biossusa.com/api/distributor?key= ***********。 No&#39; Access-Control-Allow-Origin&#39;标头出现在请求的资源上。起源&#39; null&#39;因此不允许访问。

我需要做些什么才能防止这种情况发生?

如何继续进行调试?

我现在正在接受任何建议。

任何提示/建议/帮助都将非常感谢!

0 个答案:

没有答案