当前位置: 代码迷 >> 综合 >> Laravel6.X 跨域问题解决方案
  详细解决方案

Laravel6.X 跨域问题解决方案

热度:78   发布时间:2024-03-07 00:44:16.0

Laravel6.X 跨域问题解决方案

简要说明:新项目比较小,所以尝试了 6.0 版本的 Laravel 框架。之前的项目用的是 barryvdh/laravel-cors 这个包,但是目前不支持 6.X 系统的,所以贴出这个项目的解决方案。

自定义中间件

第一步:创建中间件

php artisan make:middleware EnableCrossRequestMiddleware

第二步:编辑中间件

<?php
namespace App\Http\Middleware;
use Closure;
class EnableCrossRequestMiddleware{/*** @param $request* @param Closure $next* @return mixed*/public function handle($request, Closure $next){header('Content-Type: text/html;charset=utf-8');header('Access-Control-Allow-Origin:*');header('Access-Control-Allow-Methods:POST,GET,PUT,OPTIONS,DELETE'); // 允许请求的类型header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookiesheader('Access-Control-Allow-Headers: Content-Type,Access-Control-Allow-Origin,Access-token,Content-Length,Accept-Encoding,X-Requested-with, Origin,Access-Control-Allow-Methods'); // 设置允许自定义请求头的字段return $next($request);}
}

第三步:注册中间件(全局)

<?phpnamespace App\Http;use Illuminate\Foundation\Http\Kernel as HttpKernel;class Kernel extends HttpKernel
{/*** The application's global HTTP middleware stack.** These middleware are run during every request to your application.** @var array*/protected $middleware = [//other\App\Http\Middleware\EnableCrossRequestMiddleware::class,];
Copy

 跨域

  相关解决方案