Allow CORS in Laravel or Lumen

首先创建一个中间件,lumen 需要手动创建

php artisan make:middleware Cors

更新 app/Http/Middleware/Cors.php

<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
  public function handle($request, Closure $next)
  {
    return $next($request)
      ->header("Access-Control-Allow-Origin", "*")
      ->header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
      ->header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Token-Auth, Authorization");
  }
}

Laravel: 注册中间件到 app/Http/kernel.php

protected $routeMiddleware = [
  "auth" => \App\Http\Middleware\Authenticate::class,
  "auth.basic" => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
  "guest" => \App\Http\Middleware\RedirectIfAuthenticated::class,
  "cors" => \App\Http\Middleware\Cors::class, // <-- add this line
];

Lumen: 修改 bootstrap/app.php

$app->routeMiddleware([
    'auth' => App\Http\Middleware\Authenticate::class,
    "cors" => App\Http\Middleware\Cors::class,
]);

最后,您想要启用CORS的任何路由,只需在路由注册中添加此中间件。

Laravel, add test routers in routes/api.php

// http://docker.local/api/v1/base
// without auth
Route::group(['prefix' => 'v1',  'middleware' => ['api', 'cors']], function () {
 Route::get('/base', 'Controller@base')->name('api.v1.base');
});

// with auth
Route::group(['prefix' => 'v1',  'middleware' => ['auth:api', 'cors']], function () {
 Route::get('/base', 'Controller@base')->name('api.v1.base');
});

Lumen:

$router->group(['middleware' => 'cors'], function () use ($router) {
    $router->group(['prefix' => 'blog/v1'], function () use ($router) {
        $router->get('/hello', function () use ($router) {
            return [
                'version' => $router->app->version(),
                'app' => 'hello'
            ];
        });
    });
});