[SOLVE] Simple But Work | Step to Solve Axio Cross-Origin For Restful API Lumen 5.7

Chalid Ade Rahman
2 min readFeb 5, 2020

--

I’m Laravel user and i use Lumen for microservices. It mean i’m focuse build backend system or logical system with API. When i’ve done with my backend system specially my Restfull API. I had some problem when i call my API with axios.js. The problem is Blocked Cross-Origin, if you’re developer i know maybe this is a very general problem when you separate between front-end and back-end.

I try to solve this and fortunately i found very simple way to solve this problem. Very simple. You only need Two step.

Step 1: Set Up a CORS Middleware

Open your app\Http\Middleware folder, then create new file and save with filename as CorsMiddleware.php . Yeah you know, you can name it anything that you want but for easily just give it name like that.

Open File and Copy — Paste this script.

As you know, we create new middleware which will responsible for our interception of all request in our API. We will adding access control headers alongside a status code of 200. It mean Status OK. Now let’s do Step 2.

Step 2: Register New Middleware

Let’s move and open bootstrap/app.php file. In this file we will register our new middleware that we have create. Just Adding following lines:

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

if you changing name of middleware file don’t forget to change CorsMiddleware with name of your corsmiddleware file. What’s next ? Try to call your api again and foila !!

It Work

You have some problem, let me know how you solve it in comment below.

--

--

Chalid Ade Rahman
Chalid Ade Rahman

Written by Chalid Ade Rahman

PHP Programmer | PT Electronic Data Interchange Indonesia | Question : chalidade@gmail.com

No responses yet