Laravel POST request Cors No 'Access-Control-Allow-Origin'

16,562

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
Share:
16,562
kalenpw
Author by

kalenpw

Fullstack developer for APG, mainly writing PHP, Python, and JavaScript. CS degree from Idaho State University.

Updated on June 05, 2022

Comments

  • kalenpw
    kalenpw almost 2 years

    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
    kalenpw about 5 years
    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
    kalenpw about 5 years
    github.com/barryvdh/laravel-cors did the trick. Thank you for the suggestion.