1.安装中间件
php artisan make:middleware EnableCrossRequestMiddleware
2.配置中间件
public function handle($request, Closure $next) { $response = $next($request); $origin = $request->server('HTTP_ORIGIN') ? $request->server('HTTP_ORIGIN') : ''; $allow_origin = [ 'http://localhost:9527',//允许访问 ]; if (in_array($origin, $allow_origin)) { $response->header('Access-Control-Allow-Origin', $origin); $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN'); $response->header('Access-Control-Expose-Headers', 'Authorization, authenticated'); $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS'); $response->header('Access-Control-Allow-Credentials', 'true'); } return $response; }
3.添加中间件
\App\Http\Middleware\EnableCrossRequestMiddleware::class