3

Currently receiving an error message when I attempt to POST to a given url. GET works fine on the same domain here is my error:

Access to XMLHttpRequest at 'http://localhost:8000/api/users/login' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I've found countless questions documenting this same issue all with variations of modify my Cors middleware.

Currently my CORS middleware looks like this:

class Cors
{
    public function handle($request, Closure $next)
    {
        if ($request->isMethod('OPTIONS')) {
            $response = Response::make();
        } else {
            $response = $next($request);
        }
        return $response
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');
    }
}

The error states No 'Access-Control-Allow-Origin' which I believe my ->header('Access-Control-Allow-Origin', '*') should handle since the * is a wild card from my understanding. Is there a different issue at play here I'm missing? Stack is Laravel backend with VueJS front end using Axios for HTTP requests if that is relevant.

Edit: This question is unique in that I already have the headers suggested in most answers specifically:

->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')

and am still getting the error.

kalenpw
  • 695
  • 3
  • 10
  • 34
  • Possible duplicate of [Adding Access-Control-Allow-Origin header response in Laravel 5.3 Passport](https://stackoverflow.com/questions/39429462/adding-access-control-allow-origin-header-response-in-laravel-5-3-passport) – Jigar Mar 12 '19 at 06:42
  • @jigarhalani that was actually one of the first answers I've found. I tried that initially and it didn't work, but either way I still have both things that answer recommends in my headers. – kalenpw Mar 12 '19 at 06:47

1 Answers1

6

Here are two packages which can help you handling CORS in Laravel, you can choose one


  1. https://github.com/barryvdh/laravel-cors
  2. https://github.com/spatie/laravel-cors
  • Currently taking a look at the barrvdh package. If this solves the issue and no one posts an answer with how to fix my current implementation I'll accept this answer. – kalenpw Mar 12 '19 at 07:01
  • https://github.com/barryvdh/laravel-cors did the trick. Thank you for the suggestion. – kalenpw Mar 12 '19 at 07:09