Leon Revill Leon Revill - 1 year ago 70
AngularJS Question

Routing issue with Laravel, AngularJS and CORS

I have been searching far and wide for a solution to this problem.

I have an AngularJS web app with a Laravel 4 backend implementation as follows:

http://app.mydomain.io/ = AngularJS web app
http://api.mydomain.io/ = Laravel Back-end

Within the routes.php file in Laravel I have the following PHP code to set the Access-Control headers:

header('Access-Control-Allow-Origin: http://app.mydomain.io');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');

I also have a route set-up for a login request as follows:

Route::post('/login', function()
$email = Input::get('email');
$password = Input::get('password');
if (Auth::attempt(array('email' => $email, 'password' => $password)))
return "Success!";
} else {
return "Fail!";

In AngularJS I have a AuthService which looks like below:

app.factory('AuthService', ['$resource', '$q', '$cookieStore', function($resource, $q, $cookieStore) {
var user = null;
var Service = $resource('//api.mydomain.io/login/', {}, {});
return {
login: function(email, password) {
var deferred = $q.defer();
Service.save({email: email, password: password}, function(response) {
$cookieStore.put('user', JSON.stringify(response));
}, function(error) {
return deferred.promise;

When this request is made I get the following:

XMLHttpRequest cannot load http://api.mydomain.io/login. Invalid HTTP status code 404

If I change the Laravel route and AngularJS service to use GET, everything works as expected. The problem stems from AngularJS .save() making a OPTIONS request instead of POST (I don't fully understand why).

Could anyone help me with the proper and best practice solution?

Thank you!

Answer Source

The following solution worked:

Within filters.php add the following:

    if (Request::getMethod() == "OPTIONS") {
        $headers = array(
            'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers'=> 'X-Requested-With, content-type',);
        return Response::make('', 200, $headers);

And at the top of routes.php add the following:

header('Access-Control-Allow-Origin: http://app.mydomain.io');

Thanks to the Google Plus community! :)