Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-Origin Request Blocked error with Laravel, barryvdh/laravel-cors & axios on a 404 response

I'm using Laravel with laravel-cors package as the back-end. I'm making API request with axios from a different domain. Basically everything works fine.

Then I created this new route to retrieve a single object by id. When an object with the id exists I get a normal response with the data. When it doesn't - I get a normal 404 response (checked in the network tab), except in the console I get this error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://... (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Also, axios determines it not as a 404 error, but as an unknown "Network Error". I can't act on this response properly in my SPA and I believe this is not an expected behavior.

like image 644
Alexander Avatar asked Feb 27 '18 10:02

Alexander


Video Answer


1 Answers

The problem was with the barryvdh/laravel-cors package's middleware. Applying it before any other middleware has fixed the problem, i.e. I had to change this:

'api' => [
    'throttle:60,1',
    'bindings',
    \Barryvdh\Cors\HandleCors::class,
],

to this:

'api' => [
    \Barryvdh\Cors\HandleCors::class,
    'throttle:60,1',
    'bindings',
 ],
like image 67
Alexander Avatar answered Nov 15 '22 03:11

Alexander