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

1

5

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.

Paronymous answered 27/2, 2018 at 10:9 Comment(0)
P
10

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',
 ],
Paronymous answered 27/2, 2018 at 10:23 Comment(1)
Did not work, Laravel 8 - 2022Fancher

© 2022 - 2024 — McMap. All rights reserved.