1、先检查app/Http/Middleware/ 下是否有EnableCrossRequestMiddleware.php 这个文件,没有此文件使用此命令创建
1 php artisan make:middleware EnableCrossRequestMiddleware
2、然后修改EnableCrossRequestMiddleware.php 的handle
1 /** 2 * Handle an incoming request. 3 * 4 * @param IlluminateHttpRequest $request 5 * @param Closure $next 6 * @return mixed 7 */ 8 public function handle($request, Closure $next) 9 { 10 $response = $next($request); 11 $origin = $request->server('HTTP_ORIGIN') ? $request->server('HTTP_ORIGIN') : ''; 12 $allow_origin = [ 13 'http://127.0.0.1:8080',//允许访问 14 ]; 15 if (in_array($origin, $allow_origin)) { 16 $response->header('Access-Control-Allow-Origin', $origin); 17 $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN'); 18 $response->header('Access-Control-Expose-Headers', 'Authorization, authenticated'); 19 $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS'); 20 $response->header('Access-Control-Allow-Credentials', 'true'); 21 } 22 return $response; 23 }
3、找到app/Http/Kernel.php文件中的 protected $middleware
1 protected $middleware = [ 2 AppHttpMiddlewareCheckForMaintenanceMode::class, 3 IlluminateFoundationHttpMiddlewareValidatePostSize::class, 4 AppHttpMiddlewareTrimStrings::class, 5 IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class, 6 AppHttpMiddlewareTrustProxies::class, 7 AppHttpMiddlewareEnableCrossRequestMiddleware::class,//新增跨域中间件 8 ];