Reputation: 1202
I know this is a very common problem and there is a lot of other questions about it, however, I don't know what to do anymore. I have upgraded my Laravel API application from 5.8
to 7.10.3
and now I'm facing this CORS
issue that didn't happen before. Laravel 7 already provides the fruitcake/laravel-cors
package and this is my configuration (default config) in config/cors.php
:
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
Basically every origin
, headers
and methods
are allowed. I've even tried to add these lines to bootstrap/app.php
but it won't worked:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: *');
My frontend is built with VueCli 3
and I didn't make any changes on it, just upgraded Laravel version.
Requests on POSTMAN
are working fine. Does anyone have any idea of why this problem is happening?
Full error message:
Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/operacao/cadastrar' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Upvotes: 2
Views: 9746
Reputation: 1202
I've found the problem: My request was failing in the $request->validate()
method and it was inside a try / catch
block with a custom exception handler like this:
try {
$request->validate(array(...)); //validation was failing
//code...
} catch (\Exception $e) {
//This was the problem
http_response_code(400);
die($e->getMessage());
}
Just put $request->validate()
before try
and it worked. Just remembering that validate()
has its own exception handler.
I don't know exactly why this was causing a CORS error but I think that's because it was sending the headers
before the Access-Control-Allow-Origin
etc.
Upvotes: 1
Reputation: 871
I had a similar issue using REACT and my solution was to add Headers and format my request like this.
axios.request({
method: "POST",
url: '<url>',
data: data,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
})
.then(function (response) {
<what to do if works>
})
.catch((response) => {
<what to do if it doesn't work>
})
Upvotes: 0