Joseph Khella
Joseph Khella

Reputation: 715

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

Upvotes: 0

Views: 1854

Answers (3)

Nikhil Radadiya
Nikhil Radadiya

Reputation: 2065

You can also consider using this package.

Upvotes: 0

Joseph Khella
Joseph Khella

Reputation: 715

SOLVED

It turned out to be something with chrome itself, the app works just fine on edge or any browser,, in order to make it work on chrome,, install this plugin. https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi/related?hl=en

Upvotes: 0

Oluwafemi Sule
Oluwafemi Sule

Reputation: 38982

The preflight request is a HEAD request. You should list it in Access-Control-Allow-Methods.

Your handle will be like so:

public function handle($request, Closure $next)
{
    $response = $next($request);
    $response->header('Access-Control-Allow-Methods', 'HEAD, GET, POST, PUT, PATCH, DELETE');
    $response->header('Access-Control-Allow-Headers', $request->header('Access-Control-Request-Headers'));
    $response->header('Access-Control-Allow-Origin', '*');
    return $response;
}

Upvotes: 2

Related Questions