Skip to content

Instantly share code, notes, and snippets.

@falmar
Forked from danharper/CatchAllOptionsRequestsProvider.php
Last active February 22, 2021 14:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save falmar/9e1dea3ff973d685da85e328c799a9f4 to your computer and use it in GitHub Desktop.
Save falmar/9e1dea3ff973d685da85e328c799a9f4 to your computer and use it in GitHub Desktop.
Enable CORS in Lumen 5.2 - ServiceProvider + Middleware
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$request = app('request');
// ALLOW OPTIONS METHOD
if($request->getMethod() === 'OPTIONS') {
app()->options($request->path(), function () {
return response('OK',200)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods','OPTIONS, GET, POST, PUT, DELETE')
->header('Access-Control-Allow-Headers', 'Content-Type, Origin');
});
}
}
}
<?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)
{
$response = $next($request);
$response->header('Access-Control-Allow-Origin','*');
return $response;
}
}

Because lumen does not allow OPTIONS method and will return status response 405 MethodNotAllowed unless you explicitly add it your routes $app->options('my-route', function(){}), that is why the request do not hit the middleware. in my case this was happening using react and I was stuck for almost one hour trying to figure out what was wrong, until I found this and everything make sense.

But this service provider was not working without adding extra headers apparently the preflight request need this headers in response as well:

  • Access-Control-Allow-Origin: *
  • Access-Control-Allow-Headers: Content-Type, Origin

Otherwise I would the following errors:

  • Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'my-host' is therefore not allowed access.
  • Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response

But following this amazing CORS tutorial: http://www.html5rocks.com/en/tutorials/cors/ changed the original files to make them work. Tested in Lumen 5.2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment