0

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

3 Answers 3

2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

thx for your reply,,, I don't really get it, shall I make it like GET, POST, PUT, DELETE, OPTIONS, HEAD ? i tried this and still not working
0

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

Comments

0

You can also consider using this package.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.