Fix Error “CORS” For Laravel Lumen Application


I am developing an Ionic apps and a Lumen application as REST API. This Lumen deployed in Docker container with port 81 exposed while the Ionic run in chrome browser. The communication between them figured as below:

When I ran the ionic it’s showing CORS error and caused the app stop working.


According to Mozilla developer website, CORS happen when a web application tried to send requests to resource that has a different origin (domain, protocol, and port) than its own origin. In my case, http request was made from same host as target resource (localhost) but different port number.


If you google “how to fix/allow CORS” then you’ll find some websites tells you to add extra headers to your HTTP response by modifying web server configuration. But there is another way you can do in case you have a very little experience with server configuration or you were unable to reach infra guys to ask their help, fix it with Middleware.

Middleware is a mechanism for filtering HTTP request coming to your application so you can easily modify HTTP Request and Response in a very convenient way.

Now let’s get to step-by-step:

Create a new file CorsMiddleware.php inside directory app\Http\Middleware

This class is used to modify Http Response header, what important here is line number 22 where we tell browser to accept request from any sources (*)

'Access-Control-Allow-Origin' => '*'

In order to make CorsMiddleware class known by Lumen next we have to Register it in app\bootstrap\app.php

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

Now we should find that error no more.



enterprise architect. tech enthusiast. coffee addict.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store