How to solve – No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘null’ is therefore not allowed access.
In this short post, I will show you how to solve the “No ‘Access-Control-Allow-Origin'” problem for a Laravel/Lumen API, using the nordsoftware/lumen-cors.
Packages you could use to solve this issue:
Why do you get this problem?
Chances are that you are getting this error when you’re trying to make a call to an API or trying to get some data from a different domain to the one your application is using. Simply put, you get this problem because cross-domain communication is not allowed by your browser. A good example would be: allbooks.com is an API that returns information about all the books in the world, seebooks.com is a website that gets the information from allbooks.com and displays it in a nice user interface.
What is CORS?
You can read the official documentation of CORS to get a better understanding of CORS. In principle, all CORS is doing is to allow cross-domain communication from the browser. For example, it will allow seebooks.com to get the data that it needs from allbooks.com
How to solve it?
I usually use nordsoftware/lumen-cors package to solve this issue, but you could solve it using other similar packages as well. In principle, all you need to do is follow their instructions and everything should work, but there’s always a step that I miss or something that I’m doing wrong and it ends up not working. By following the steps below it should work correctly every time you need to use it:
- Install the package via composer:
composer require nordsoftware/lumen-cors
By running the above command you should see the same output in the terminal as the one from the picture above. Once the command is executed, check the vendor directory. There you should see the /nordsoftware folder, as the one from the picture above.
- Copy config folder from nordsoftware/lumen-cors/config into the root directory of your project, so myproject/.
- Add the following lines to the bootstrap/app.php file:
$app->middleware([ ..... 'Nord\Lumen\Cors\CorsMiddleware', ]);
Your application should now successfully handle CORS requests.
Let me know in the comments if you need any help.