Laravel angularJS CORS using barryvdh/laravel-cors

2019-06-25 12:44发布

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

2条回答
贼婆χ
2楼-- · 2019-06-25 12:55

Finally, I found the proper solution for my situation:

  1. I completely get rid the barryvdh/laravel-cors
  2. 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 :)

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-06-25 13:09

I recently update my laravel-cors package so you might want to check it again. But setting the Access-Control-Allow-Origin: * header directly (with the response object) also works, it just doesn't check for allowed hosts, headers and methods etc.

A more Laravel way of setting the header would be to define a Route filter and modify the response there.

Route::filter('access-control', function($route, $request, $response)
{
    $response->headers->set('Access-Control-Allow-Origin', '*');
});

Then you can set the afterFilter in your Controller, or attach it to a group of routes in your routes.php file.

public function __construct()
{
    $this->afterFilter('access-control');
}

or apply it when it matches a pattern:

Route::when('api/*', 'access-control');

I would avoid using the header() function directly. Also, you are setting the headers both in Nginx and in Laravel, one would suffice.

查看更多
登录 后发表回答