网上很多针对 Laravel 版本的扩展包能解决跨域问题,比如 fruitcake/laravel-cors、barryvdh/laravel-cors 等,但是在 Laravel11下,都无法安装,原因是版本太高了,以下采用另一种方式来解决跨域问题,也就是中间件的形式。
1、首先创建跨域中间件 CheckCors.php
php artisan make:middleware CheckCors
2、编写中间件跨域代码
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class CheckCors { /** * Handle an incoming request. * 跨域中间件 * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $response = $next($request); $response->header('Access-Control-Allow-Origin', '*'); $response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); $response->header('Access-Control-Allow-Headers', 'Content-Type, Authorization'); return $response; } } ?>
3、注册中间件
打开 /bootstrapapp.php 文件,在中间件里面加入如下代码
$middleware->appendToGroup('CheckCors', [ App\Http\Middleware\CheckCors::class, ]); //跨域
示例:
<?php use Illuminate\Foundation\Application; use Illuminate\Foundation\Configuration\Exceptions; use Illuminate\Foundation\Configuration\Middleware; return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__.'/../routes/web.php', commands: __DIR__.'/../routes/console.php', health: '/up', ) ->withMiddleware(function (Middleware $middleware) { $middleware->appendToGroup('CheckCors', [ App\Http\Middleware\CheckCors::class, ]); //跨域 }) ->withExceptions(function (Exceptions $exceptions) { // })->create(); ?>
4、在路由定义文件中使用中间件
打开 routes/routes/api.php 这里博主在 api.php 里面使用跨域中间件
<?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; Route::post('admin/login', [App\Http\Controllers\Admin\LoginController::class, 'login'])->middleware('CheckCors')->name('admin.login.login'); ?>
文章评论(0)