Laravel 8 CORS issues for apis

  api, cors, javascript, laravel, laravel-8

I’m using Laravel 8 as my project’s back end and NextJS for front end.
When I call an API using axios sometimes I get CORS error in browsers console and sometimes not.
For example if I get information of 5 products with that API, I won’t get any error and ‘Access-Control-Allow-Origin’ header exists in the response header but When I get information of 20 products (response size increases but not too much), I get CORS error and surprisingly ‘Access-Control-Allow-Origin’ header does not exist in response header.

I tested this API with postman and got the same result. (‘Access-Control-Allow-Origin’ header disappears)

I’ve tried every thing that I found on the Internet such as :

  1. Creating a Middleware and assigning it to the API or whole application and with this body:

return $next($request)->header(‘Access-Control-Allow-Origin’, ‘*’)->header(‘Access-Control-Allow-Methods’, ‘PUT,POST,DELETE,GET,OPTIONS’)->header(‘Access-Control-Allow-Headers’, ‘Accept,Authorization,Content-Type’);

  1. using some headers on top of my api.php file

  2. using ajax instead of axios

I just search everything that you can find on Internet about this topic and found nothing.

This is so pain in the neck because I don’t get CORS error on some APIs and get that error for rest of them.

I’m stuck because of this problem for at least 2 days!

I appreciate anyone who can help me out with this problem!

Source: Laravel

Leave a Reply