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
Finally, I found the proper solution for my situation:
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 :
And it works like a boss :)
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.
Then you can set the afterFilter in your Controller, or attach it to a group of routes in your routes.php file.
or apply it when it matches a pattern:
I would avoid using the header() function directly. Also, you are setting the headers both in Nginx and in Laravel, one would suffice.