My API is built with Laravel version 5.6 and my front-end uses React with Redux. I'm facing the CORs problem when attempting to connect to the API.
Failed to load http://127.0.0.1:8000/api/login: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I tried applying the solutions I found around. I have my Cors
middleware class:
public function handle($request, Closure $next)
{
return $next($request)
->header("Access-Control-Allow-Origin", "http://localhost:3000") // Already tried with *
->header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
->header("Access-Control-Allow-Headers", "Content-Type, Authorization");
}
And the Kernel.php
:
protected $middlewareGroups = [
...,
'api' => [
...
'cors'
],
];
protected $routeMiddleware = [
...
'cors' => \App\Http\Middleware\Cors::class
];
The routes:
Route::post("/login", "Api\UserController@login");
Route::post("/register", "Api\UserController@register");
Route::prefix("users")->group(function () {
Route::middleware("auth:api")->group(function () {
Route::get("me", "Api\UserController@details");
});
});
And the action:
export function login(data) {
return dispatch => {
return dispatch({
[RSAA]: {
endpoint: "http://127.0.0.1:8000/api/login",
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
types: [LOGIN, LOGIN_SUCCESS, LOGIN_FAILURE]
}
})
}
}
In the headers of the request, I can see the CORs methods that were sent. So what's missing?