Skip to content

Instantly share code, notes, and snippets.

@fifths
Last active June 6, 2018 17:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fifths/81a5c0332c799078cb886fef5fc1467c to your computer and use it in GitHub Desktop.
Save fifths/81a5c0332c799078cb886fef5fc1467c to your computer and use it in GitHub Desktop.
Lumen with CORS requests

Add the CorsMiddleware to the bootstrap/app.php

$app->middleware([
    App\Http\Middleware\CorsMiddleware::class
]);

or

$app->routeMiddleware([
    'cors' => App\Http\Middleware\CorsMiddleware::class
]);

can solved

OPTIONS http:// 405 (Method Not Allowed)

XMLHttpRequest cannot load http://. Response for preflight has invalid HTTP status code 405

<?php
namespace App\Http\Middleware;
use Symfony\Component\HttpFoundation\Response;
class CorsMiddleware
{
public function handle($request, \Closure $next)
{
$headers = [
'Content-type' => 'application/json;charset=UTF-8',
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'HEAD,GET,POST,PUT,PATCH,DELETE,OPTIONS',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => '86400',
'Access-Control-Allow-Headers' => $request->header('Access-Control-Request-Headers')
];
if ($request->isMethod('OPTIONS')) {
return response()->json('{"method":"OPTIONS"}', 200, $headers);
}
$response = $next($request);
foreach ($headers as $key => $value) {
$response->headers->set($key, $value);
}
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment