I'm trying to enable CORS in Lumen 5.8 backend api system, called by a React Js frontend.
Here what I did:
- I've created CatchAllOptionsRequestsProvider.php to App\Providers folder.
use Illuminate\Support\ServiceProvider;
/**
* If the incoming request is an OPTIONS request
* we will register a handler for the requested route
*/
class CatchAllOptionsRequestsProvider extends ServiceProvider {
public function register()
{
$request = app('request');
if ($request->isMethod('OPTIONS'))
{
app()->options($request->path(), function() { return response('', 200); });
}
}
}
- Then I've created CorsMiddleware.php
<?php
namespace App\Http\Middleware;
use Closure;
class CorsMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
//Intercepts OPTIONS requests
if($request->isMethod('OPTIONS')) {
$response = response('', 200);
} else {
// Pass the request to the next middleware
$response = $next($request);
}
// Adds headers to the response
$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', '*');
// Sends it
return $response;
}
}
- In bootstrap/app.php I've added this:
$app->middleware([
App\Http\Middleware\CorsMiddleware::class
]);
$app->register(App\Providers\CatchAllOptionsRequestsProvider::class);
As result I get this error in bootstrap/app.php file: PHP Fatal error: Uncaught Error: Call to undefined method Illuminate\Foundation\Application::middleware() in /bootstrap/app.php:44
I don't wanna install any package, I've already tried without getting results, I'd like just to fix this error, because I guess it could be work. Could you please help me??
Thanks in advance for your answers.
source https://stackoverflow.com/questions/69742881/lumen-5-8-enable-cors
Comments
Post a Comment