I'm struggling with this issue, i have and API made in Laravel, one of endpoints needs to be accesible to others servers that make a request, i read several forums, here, i and could'nt find a solution.
This the error that throws me in the front:
Access to fetch at 'http://localhost:8000/api/v1/auth/signup' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
i tried to implement a cors middleware, this the code:
<?php namespace App\Http\Middleware;
use Closure;
class CORS {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
header("Access-Control-Allow-Origin: *");
// ALLOW OPTIONS METHOD
$headers = [
'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
];
if($request->getMethod() == "OPTIONS") {
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
return Response::make('OK', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
$response->header($key, $value);
return $response;
}
}
in kernel.php:
protected $routeMiddleware = [
'cors' => \App\Http\Middleware\Cors::class,
in the routes.php:
Route::post('api/v1/auth/signup', 'Api\AuthApiController@signUpUser')->middleware(['cors']);
Why the cors middleware is not doing nothing? From the server side there's no errors.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire