Dealing with CORS in Laravel/Lumen framework

Nahuel Bulian
1 min readMay 28, 2020

--

For those who are struggling with CORS policies, here is the solucion.

What’s is CORS? CORS stands for Cross-Origin Resource Sharing, is a method that browsers uses to let HTTP calls to obtain access to resources on a distinct origin.

The problem…

CORS policy in action!

What you are seen in the image above, is a front-end sending a post request through Axios to a Lumen API back-end.

The solution…

Lumen does not recognize OPTIONS request method and rejects it with an http status 508. So we need first we need to create a middleware which is going to respond with a http code 200 in case the browser send an OPTIONS request. Sometimes browsers send it first as a form of verification request.

Let’s create a file called CorsMiddleware.php into your app\Http\Middleware folder with the following code:

Last step, register the new middleware in your bootstrap/app.php by adding this lines in the Middleware Registration Section.

$app->middleware([
App\Http\Middleware\CorsMiddleware::class
]);

That’s it all! Your API is ready to respond to your javascript requests!

Happy coding!

--

--

Nahuel Bulian
Nahuel Bulian

Written by Nahuel Bulian

#Entrepreneur, tech developer & #crypto enthusiast #bitcoin #ethereum

Responses (1)