I have an application in Lumen inside a docker container, to which I make requests locally through postman and it works correctly, but when I make the same call from a react application locally, I get a CORS error.
The call from React
const loginPayload = {
email: this.state.input_email,
password: this.state.input_password,
}
const config = {
headers: {
'Access-Control-Allow-Origin': '*'
}
}
axios.post("http://192.168.1.149:8081/u/login", loginPayload, config)
.then(response => {
//get token from response
const token = response.data.token;
//set JWT token to local
localStorage.setItem("token", token);
//set token to axios common header
this.setToken(token);
//redirect user to home page
window.location.href = '/'
})
.catch(err => console.log(err));
And my Lumen configuration
namespace App\Http\Middleware;
use Closure;
class CorsMiddleware
{
public function handle($request, Closure $next)
{
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => '86400',
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With'
];
if ($request->isMethod('OPTIONS')) {
return response()->json('{"method":"OPTIONS"}', 200, $headers);
}
$response = $next($request);
foreach ($headers as $key => $value) {
$response->header($key, $value);
}
return $response;
}
}
Routes file:
$router->group(['middleware' => ['cors']], function () use ($router) {
$router->post('u/login', 'UserController@authenticate');
});
I'm trying to make a call to my api but it returns an error in localhost
CodePudding user response:
You're sending a response header (Access-Control-Allow-Origin
) with your request:
const config = {
headers: {
'Access-Control-Allow-Origin': '*'
}
}
axios.post("http://192.168.1.149:8081/u/login", loginPayload, config)
But your CORS configuration server-side doesn't allow that request header:
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With'
...so the request doesn't pass the check.
Remove the invalid header from your request.
Generally, to diagnose these issues, compare the headers and other information in the request you're sending (via the Network tab in the browser) to your CORS configuration, and look for mismatches.