CORS Laravel, how to fix it ?

CORS (Cross-Origin Resource Sharing) is a system that allows you to know who can access the data of your Laravel backend (see other frameworks such as Symfony or Nodejs etc. it is the same principle).

CORS problem

The problem is that when you want to access the data of your API via a front framework for example React or Vue, your API rejects you with a cross-origin error, this comes from the fact that your back has not been configured to understand that you have the right via your front, to access the data that the back provides.

Solution

The fastest solution that does not require installing an external package is this:

Add this piece of code at the top of your file that contains your routes to call.


header('Access-Control-Allow-Origin:  *');
header('Access-Control-Allow-Methods:  POST, GET, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers:  Content-Type, X-Auth-Token, Origin, Authorization');

This will add the necessary headers for your back to accept all the time and for each HTTP method, big worry once in production for example anyone can access your back. If you want to secure your backend you have to add the url of your frontend instead of the “*”, like this :

header('Access-Control-Allow-Origin:  http://localhost:8080');

This ensures that only your front end at this address will be able to access the data, people trying to access your data via other urls will receive a CORS error.

Package that manages CORS

There is a package that handles CORS, this is a cleaner way than pasting headers directly into your file.

Managing CORS via the fruitcake package in Laravel 8