Sephen
Sephen

Reputation: 1111

Laravel Lumen 5.2 Cors Middleware not working

In Laravel Lumen 5.1 i am using this in my CorsMiddleware:

public function handle($request, \Closure $next)
{
    $response = $next($request);
    $response->header('Access-Control-Allow-Methods', 'HEAD, GET, POST, PUT, PATCH, DELETE');
    $response->header('Access-Control-Allow-Headers',  $request->header('Access-Control-Request-Headers'));
    $response->header('Access-Control-Allow-Origin', '*');
    return $response;
}

But in 5.2 its not working anymore.

How do i return the appropriate headers in the response?

Upvotes: 2

Views: 2796

Answers (2)

Serhii Matrunchyk
Serhii Matrunchyk

Reputation: 9363

Put all your routes inside to enable web middleware group:

Route::group(['middleware' => ['web']], function () {
    // Here comes your routes
});

Upd.

To resolve this, please use this package: github.com/barryvdh/laravel-cors

Upvotes: 1

Kocik
Kocik

Reputation: 504

Browsers use OPTIONS requests to check if you have any CORS headers on your endpoint. Which means, that you need to care of those pre-flight OPTIONS requests first, providing them with correct headers.

In Lumen/Laravel you need to add your CORS middleware also to the same route as your CORS resource, but requested with OPTIONS method:

$app->options(
    'your/cors/uri',
    [
        'middleware' => 'cors', function() 
         function() { return response('', 200); }
    ]
);

Had the same problem, so I hope that this helps you :)

Upvotes: 1

Related Questions