Saturday, May 20, 2017

Allow CORS With Laravel and Angular2

I'm creating a Laravel web app that will act as an API for an Angular2 app, for now i'm hosting the Laravel app on WAMP server on windows laravel is on localhost:8000 and Angular is on localhost:4200 I've created the middleware for CORS like that:

class Cors {
public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, X-Token-Auth, Authorization');
    }
}

When calling my api url I get this:

XMLHttpRequest cannot load http://localhost:8000/api/myapi. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access

I'm pretty sure it's not something with the middleware because the api works when I ng build the angular app, it just doesn't work with ng serve when serving on localhost:4200

any ideas? Thank you



via Joseph Khella

Advertisement