Laravel angularJS CORS使用barryvdh / laravel-cors

前端之家收集整理的这篇文章主要介绍了Laravel angularJS CORS使用barryvdh / laravel-cors前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
已经六个小时了,我仍然无法解决以下问题.

我试图让AngularJS从不同的域名中获取我的API.在搜索互联网之后,我发现这个package它说它可以“在你的Laravel应用程序中添加CORS(跨源资源共享)标头支持

我遵循了所有指示.设置这个和那个让它工作,但仍然没有运气.我的服务器总是向我发送以下错误

XMLHttpRequest cannot load 07001. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘07002’ is therefore not allowed access.

这是我的Angular代码

var Demo = angular.module( "Demo",[ "ngResource" ] );
Demo.controller(
  "ListController"
  function( $scope,$http,$resource ) {

    $http.defaults.useXDomain = true;

     $scope.useResource = function() {
     var Lists = $resource('http://lab.laracon/v1/lists',{
         username: 'OSVC8HKKcvCFrsqXsMcbOVwVQvOL0wr3',password: 'whatever'
     });
     Lists.get({
         id: 1
     },function(data) {
         alert(data.ok);
     });
   };

  }
);

这是我的barryvdh laravel-cors配置文件

'defaults' => array(
        'allow_credentials' => false,'allow_origin' => array(),'allow_headers' => array(),'allow_methods' => array(),'expose_headers' => array(),'max_age' => 0,),'paths' => array(
        '^/v1/' => array(
            'allow_origin' => array('*'),// 'allow_headers' => array('Content-Type'),'allow_headers' => array('*'),'allow_methods' => array('POST','PUT','GET','DELETE','OPTIONS'),'max_age' => 3600,

最后这是我的Nginx服务器配置:

location / {

        # URLs to attempt,including pretty ones.
        try_files   $uri $uri/ /index.PHP?$query_string;

        add_header 'Access-Control-Allow-Origin' 'http://lab.angularapi';
         add_header 'Access-Control-Allow-Credentials' 'false';
         add_header 'Access-Control-Allow-Headers' '*';
         add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE';

    }

谁能帮我?我的代码和配置有什么问题?谢谢

解决方法

最后,我找到了适合我情况的解决方案:

>我完全摆脱了barryvdh / laravel-cors
>感谢Dan Horrigan的推文

Simple CORS with laravel

但是,我稍微更改了代码(我真的不知道为什么$response-> headers-> set();不能正常工作.相反,我将它添加到我的控制器:

public function __construct()
    {
        $this->afterFilter(function(){

            header('Access-Control-Allow-Origin: *');

        });
    }

它就像一个老板:)

猜你在找的Angularjs相关文章