Afrimadoni Dinata
2 min readFeb 13, 2019

--

Fix Error “CORS” For Laravel Lumen Application

Background

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.

CORS ERROR

Why it happen?

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.

Solution

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.

What is 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 The Class

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' => '*'

Register Middleware

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.

--

--