Routing issue with Laravel, AngularJS and CORS

I searched far and wide to solve this problem.

I have an AngularJS web application with Laravel 4 firewall support as follows:

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

In 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 setup for an entry 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 an AuthService that looks like this:

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));
                deferred.resolve(true);
            }, function(error) {
                deferred.reject(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 the AngularJS service to use GET, everything will work as expected. The problem is with AngularJS.save () creating an OPTIONS request instead of POST (I don't quite understand why).

Can someone help me with the right and best solution?

Thanks!

+4
4

:

filters.php :

App::before(function($request)
{
    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);
    }
});

route.php :

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

Google Plus!:)

Leon.

+7
0

I used quite some time figuring this out, and here is what I came up with:

Filters.php:

App::before(function($request)
{

    header('Access-Control-Allow-Origin: http://app.mydomain.io');
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization');

    // Pre-flight request handling, this is used for AJAX
    if($request->getRealMethod() == 'OPTIONS')
    {
        Log::debug('Pre flight request from Origin'.$rq_origin.' received.');
        // This is basically just for debug purposes
        return Response::json(array('Method' => $request->getRealMethod()), 200);
    }
});

App.js (Frontend):

app.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    $httpProvider.defaults.withCredentials = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];

}]);

Also note that there is an error with self-signed SSL certificates in Chrome and CORS requests, I will provide a link if you are interested in this.

Therefore, it is recommended to use Firefox during debugging (or DevHTTPClient on Chrome works fine for me).

Hurrah!

0
source

Try this piece for newer versions of Laravel (5+)

public function handle($request, Closure $next)
{
    $method = $request->method();
    if($method == "OPTIONS"){
       return response('It\ supported. Relax!', 200); 
    }
    return $next($request);
}
0
source

Source: https://habr.com/ru/post/1525282/


All Articles