I'm trying to send a post request from my frontend ( Ionic ) to my backend Laravel ! it return that Cors error. I've already made the Cors class in Laravel and added it the routeMiddleware, I have also tried the solution made by barryvdh and it's also not working. when I try the request using the get method it works but it's not the same case while using post method.
here my handle method in Cors class in laravel :
public function handle($request, Closure $next)
{
header("Access-Control-Allow-Origin: *");
// ALLOW OPTIONS METHOD
$headers = [
'Access-Control-Allow-Origin'=> '*',
'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;
}
middleware array in Kernel.php
protected $middleware = [
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\Cors::class,
];
api part of the middlewareGroups array in Kernel.php
'api' => [
'throttle:60,1',
'bindings',
\App\Http\Middleware\Cors::class,
]
routeMiddleware array in Kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'jwt.auth' => Tymon\JWTAuth\Http\Middleware\Authenticate::class,
'jwt.refresh' => Tymon\JWTAuth\Http\Middleware\RefreshToken::class,
'cors' => \App\Http\Middleware\Cors::class,
];
The route I'm trying to call
Route::post('auth/login', 'ApiController@login');
Here the code I'm executing in ionic
login(emaill: string, passwordd: string) {
return this.http.post<any>(
`${environment.laravelBackend}/auth/login`,
{ email: emaill, password: passwordd}
);
}
Anyone knows how I can make this work ? Thanks in advance