laravel 跨域解决方案

我们在用 laravel 进行开发的时候,特别是前后端完全分离的时候,由于前端项目运行在自己机器的指定端口(也可能是其他人的机器) , 例如 localhost:8000 , 而 laravel 程序又运行在另一个端口,这样就跨域了,而由于浏览器的同源策略,跨域请求是非法的。其实这个问题很好解决,只需要添加一个中间件就可以了。1.新建一个中间件

复制代码
1 php artisan make:middleware EnableCrossRequestMiddleware

2.书写中间件内容

复制代码
 1 <?php
 2 namespace App\Http\Middleware;
 3 use Closure;
 4 class EnableCrossRequestMiddleware{
 5     /**
 6      * Handle an incoming request.
 7      *
 8      * @param  \Illuminate\Http\Request $request
 9      * @param  \Closure $next
10      * @return mixed
11      */
12     public function handle($request, Closure $next){
13         $response = $next($request);
14         $origin = $request->server('HTTP_ORIGIN') ? $request->server('HTTP_ORIGIN') : '';
15         $allow_origin = [
16             'http://localhost:8000',
17         ];
18         if (in_array($origin, $allow_origin)) {
19             $response->header('Access-Control-Allow-Origin', $origin);
20             $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN');
21             $response->header('Access-Control-Expose-Headers', 'Authorization, authenticated');
22             $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
23             $response->header('Access-Control-Allow-Credentials', 'true');
24         }
25         return $response;
26     }
27 }

$allow_origin 数组变量就是你允许跨域的列表了,可自行修改。

3.然后在内核文件注册该中间件

复制代码
1 protected $middleware = [
2     // more
3     App\Http\Middleware\EnableCrossRequestMiddleware::class,
4 ];

在 App\Http\Kernel 类的 $middleware 属性添加,这里注册的中间件属于全局中间件。

然后你就会发现前端页面已经可以发送跨域请求了。

会多出一次 method 为 options 的请求是正常的,因为浏览器要先判断该服务器是否允许该跨域请求。

链接:https://mp.weixin.qq.com/s/DG0STingAz4K51i7xvF5yw

laravel 跨域解决方案 - 归一山人 - 博客园

相关推荐
不瘦80斤不改名17 小时前
Python 日志(logging)全解析
服务器·python·php
微爱帮监所写信寄信1 天前
微爱帮监狱寄信写信工具照片高清处理技术架构
开发语言·人工智能·网络协议·微信·php
天下皆白_唯我独黑1 天前
php -S 启动项目访问路由报错处理
开发语言·php
梅羽落1 天前
python武器化开发_01
开发语言·python·php
兮动人1 天前
Fatal error: Uncaught think\exception\ErrorException: SourceGuardian Loade
android·php
catchadmin1 天前
2026 年 PHP 开发者进阶 快速高效开发学习习惯
学习·php
Web极客码1 天前
深入解析WordPress的functions.php文件及其高效使用方法
开发语言·php
catchadmin1 天前
CatchAdmin 2025 年终总结 模块化架构的进化之路
架构·php·开源软件
微爱帮监所写信寄信1 天前
微爱帮监狱寄信写信小程序PHP底层优化框架
java·开发语言·数据库·spring·微信·php·mybatis