Reputation: 11
I have issue with CORS using Lumen 8.
I've created CorsMiddleware.php as this =>
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Response;
class CorsMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$headers = [
// 'Access-Control-Allow-Origin' => getenv('ACCESS_CONTROL_ALLOW_ORIGIN'),
// 'Access-Control-Allow-Methods' => getenv('ACCESS_CONTROL_ALLOW_METHODS'),
'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;
}
}
Added it in my bootstrap/app.php
$app->routeMiddleware([
App\Http\Middleware\CorsMiddleware::class,
'auth' => App\Http\Middleware\Authenticate::class,
]);
I've even add to my .htaccess
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header set Access-Control-Allow-Credentials "true"
but as useless as the rest...
And weird, Postman access to my routes !? But my local app can't...
Do you guys have an idea ?
Upvotes: 0
Views: 1125
Reputation: 384
For the Cors middleware, I think you should add it in $app->middleware([]). This is what we've done in our project before.
$app->middleware([
App\Http\Middleware\CorsMiddleware::class
]);
The $app->middleware([]}
is a global middleware and this really works very good especially when dealing with HTTP Requests.
If you would like to assign middleware to specific routes, you should first assign the middleware a short-hand key in bootstrap/app.php file's call to the $app->routeMiddleware()
. Mostly 'auth' => App\Http\Middleware\Authenticate::class,
are mostly being past here because you dealing with routes. So authenticate for protection.
#ref: https://lumen.laravel.com/docs/5.4/middleware
Upvotes: 1