Laravel angularJS CORS using barryvdh/laravel-cors

angularjs, cors, laravel, nginx

Solution

Finally, I found the proper solution for my situation:

- I completely get rid the barryvdh/laravel-cors

- Thanks for Dan Horrigan for his tweet

Simple CORS with laravel

However, I change the code little bit (I don't really know why $response->headers->set(); not working. Instead, I added this to my controller :

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

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

        });
    }

And it works like a boss :)

Problem

It's been six hour and I still don't get the solution for the following problem. I'am trying to get AngularJS hit my API from different domain. After searching the Internet I found this package that it said it can "Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application" I followed all the instructions. Set this and that to get it working but still no luck. My server always send me the same following error : XMLHttpRequest cannot load http://lab.laracon/v1/lists?id=123&password=whatever&username=OSVC8HKKcvCFrsqXsMcbOVwVQvOL0wr3. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://lab.angularapi' is therefore not allowed access. here's my Angular code: ``` 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); }); }; } ); ``` Here's my barryvdh laravel-cors config file : ``` '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, ), ), ``` and finally here's my nginx server configuration : ``` 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'; } ``` Can anyone help me? what's wrong with my code and configuration ? thanks

Original source