Lumen 8 POST request not working while GET does

  axios, cors, laravel, lumen

GET routes work when set up like so:

$router->get('/user/{id}', ['uses' => '[email protected]']);

And using this CorsMiddleware.php

public function handle(Request $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;
    }

Which gets called through Axios: this.Axios.get('http://localhost:4000/user/1') from localhost:8080

But when I try to do a POST request, this.Axios.post('http://localhost:4000/test', 'body')

I get the following error: No 'Access-Control-Allow-Origin' header is present on the requested resource.

There is an OPTIONS request being done in combination with the POST request but not the GET request. This request DOES have the headers present in CorsMiddleware.php. It seems that somehow this OPTIONS request is removing the headers from the POST request. I used Postman to verify that the API does actually work. I get the desired response there.

Source: Laravel

Leave a Reply