laravel 跨域cors中间件封装
<?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){$headers = ['Access-Control-Allow-Origin' => '*','Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE','Access-Control-Allow-Credentials' => 'true','Access-Control-Max-Age' => '86400','Access-Control-Allow-Headers' => 'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN'];//为空表示允许所有IP和域名访问$allow_origin = config('cors') ?? [];//格式:'http://127.0.0.1:8080',//允许访问$origin = $request->server('HTTP_ORIGIN') ?? $_SERVER['HTTP_ORIGIN'] ?? $request->header('Origin') ?? '';if(!empty($allow_origin) && !in_array($origin,$allow_origin)){return response()->json('Forbidden 403 ,Please add to allow access whitelist', 403, $headers);}if ($request->isMethod('OPTIONS')){return response()->json('{"method":"OPTIONS"}', 200, $headers);}$response = $next($request);foreach($headers as $key => $value){$response->header($key, $value);}return $response;}
}
有需要的可以参考