I'm trying to create a web service in Laravel 4, which will be consumed by a mobile application using AngularJS. When I make AJAX requests with AngularJS, it gives Cross Domain error because it is in another domain. How to solve?
I'm trying to create a web service in Laravel 4, which will be consumed by a mobile application using AngularJS. When I make AJAX requests with AngularJS, it gives Cross Domain error because it is in another domain. How to solve?
To enable CORS (exchange of data between different servers using AJAX), you need to make modifications to your client (AngularJS) and your server (Laravel).
In your AngularJS controller, change the $http.defaults.useXDomain
attribute to true
. It may also be necessary to remove the X-Requested-With
header, depending on the server. The configuration looks like this:
var myApp = angular.module('myApp', [
'myAppApiService']);
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
(removed from link )
From here you can make the request normally within your controller :
$scope.fazRequisicao = function() {
$http.get('http://aplicacao.com/servico')
.success(function(data) {
alert("OK");
});
};
Because of this configuration, your browser will tell the server the domain where the request is starting from, using the HTTP header Origin
.
In addition, in the server application, you must add a field to the HTTP response header, Access-Control-Allow-Origin
, indicating which domains can receive the response (or *
for any domain).
In pure PHP, this can be done by including the following line at the beginning of the code:
header("Access-Control-Allow-Origin: *");
This affects all your application's HTTP responses, allowing them to be received in any domain. This is not good security practice.
It is recommended that you allow access to only controllers . To do this, in the controllers that will be used by your client application, use a filter to add the header Access-Control-Allow-Origin
:
public function __construct()
{
$this->afterFilter(function($response)<!-- language: lang-php -->
{
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
});
}
(Source: link )
One of the best posts I saw regarding Laravel + AngularJS was this link: link