How to enable CORS support on Lumen restapi web service
This time I would like to share my experience on how to enable CORS support on Lumen restapi web service, step by step.
Before going further, we must make sure that we have a working Lumen rest api service. You can learn here at https://paulund.co.uk/creating-a-rest-api-with-lumen. By the way, I am using Lumen 5.5.
CORS (Cross-Origin Resource Sharing) is somewhat about sharing resource to client with different domain as web server. In the case here, I used Plunker site (client) to access my restapi server. Sample response of one of my restapi end point is depicted below and would be used at cors test here:
For enabling CORS support, I used a composer package called Barryvdh/Laravel-Cors. I also read tutorial about cors in hml5rocks. Ok, without further ado, lets begin the journey, step by step:
Require the barryvdh/laravel-cors package
composer require barryvdh/laravel-cors
Do the configuration
To allow CORS for all routes, add the HandleCors middleware to the global middleware (I choose this step):
but if you want to allow CORS on a specific middleware group or route, add the HandleCors middleware to your group:
Create config folder manually inside Lumen project folder, by default, config folder does not exist in root folder and then copy [myrestapi_app]/vendor/barryvdh/laravel-cors/cors.php to [myrestapi_app]/config folder. I edited the config as follows, to enable access from Plunker site:
To allow from any domain, we can set allowedOrigins to ['*']
Create web client on Plunker
Finally I create a web client at Plunker using XMLHttpRequest, check this plunk. The request would only be success if I set allowedOrigins to ['*'] or ['https://run.plnkr.co'].
Sample success alert:
Failed alert:
Chrome developer tools console would log this message:
That's all the stories. I hope you enjoyed it ^_^
Hei, Which version lumen do you use ? I didn’t see config folder in my lumen.
Lumen 5.5, thank you for your comment
Sorry, what I mean with
“And then copy manually[myrestapi_app]/vendor/barryvdh/laravel-cors/cors.php to [myrestapi_app]/config folder”,
is to create config folder manually inside Lumen project folder and then copy the cors.php config file. I have updated the article accordingly.Thanks