Skip to content

Instantly share code, notes, and snippets.

@ketavchotaliya
Forked from fifths/CorsMiddleware.php
Created April 25, 2018 08:56
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 ketavchotaliya/878b9ed1c16da3e72f9ea22067f23804 to your computer and use it in GitHub Desktop.
Save ketavchotaliya/878b9ed1c16da3e72f9ea22067f23804 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