lumen的CORS中介軟體

soonio發表於2021-01-19

今天偶然寫個demo使用一下lumen8,碰到跨域問題,處理一下

# app/Http/Middleware/CorsMiddleware.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class CorsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $headers = [
            'Access-Control-Allow-Origin'       => '*',
            'Access-Control-Allow-Credentials'  => 'false',
            'Access-Control-Allow-Methods'      => 'GET,POST,OPTIONS,DELETE,PUT',
            'Access-Control-Allow-Headers'      => '*'
        ];
        if ($request->getMethod() == 'OPTIONS') return response('', 204, $headers);

        /** @var Response $response */
        $response = $next($request);
        $response->withHeaders($headers);
        return $response;
    }
}
# bootstrap/app.php
 $app->middleware([
     App\Http\Middleware\CorsMiddleware::class
 ]);

在safari中,需要響應200才行,不然預檢會失敗

if ($request->getMethod() == 'OPTIONS') return response('', 200, $headers);
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章