Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brunocoelhor/2ab843caa7d38293e431 to your computer and use it in GitHub Desktop.
Save brunocoelhor/2ab843caa7d38293e431 to your computer and use it in GitHub Desktop.
Lumen with CORS and OPTIONS requests
<?php namespace App\Providers;
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); });
}
}
}
<?php namespace App\Http\Middleware;
class 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;
}
}

Register the CatchAllOptionsRequestsProvider service provider in bootstrap/app.php which will check the incoming request and response successfully if it is an OPTIONS request.

Add the CorsMiddleware to the $app->middleware([ array in bootstrap/app.php which will attach the following CORS headers to all responses:

  • allow all headers
  • allow requests from all origins
  • allow all the headers which were provided in the request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment