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 跨域解决方案 - 归一山人 - 博客园

相关推荐
wdfk_prog7 小时前
Wi-Fi Direct 真机实践:JOIN 建链耗时优化
服务器·asp.net·php
FungLeo10 小时前
FengCMS · PHP+MySQL 升级实录 · 数据库驱动封装:mysqli 预处理与 affected_rows 关闭后变 -1 的坑
数据库·mysql·php·工程实践·fengcms
FungLeo1 天前
FengCMS · PHP+MySQL 升级实录 ·双数据库验证:MySQL8.4与MariaDB 10.11的兼容矩阵
数据库·mysql·php·工程实践·fengcms
FungLeo1 天前
FengCMS · PHP+MySQL 升级实录 · 留言模块的六项问题:未审核进公开列表、旧回复覆盖、批量删除恢复
android·mysql·php·工程实践·fengcms
FungLeo1 天前
FengCMS · PHP+MySQL 升级实录·安全的网页安装器:一次性密钥、HTTPS+CSRF、安装锁、不删表
mysql·安全·php·安装部署·fengcms
Tanner_SL1 天前
Linux笔记之常用命令
linux·笔记·php
钉先生贾2 天前
鸿蒙启动可靠性:把首屏依赖从“同时开始”改成可降级编排【鸿蒙心迹】
华为·php·harmonyos
kingx32 天前
DASCTF BestDB 题解:双引号闭合与 union 注入回显取 flag
php·ctf·sql注入·waf绕过·union回显
FungLeo2 天前
FengCMS ·PHP+MySQL 升级实录 · 性能测量方法论:先建基线、再判定,以及为什么暂缓 UNION 改写
mysql·php·工程实践·fengcms
FungLeo3 天前
FengCMS · PHP+MySQL 升级实录 · 开源发布工程:GitHub Releases + SHA-256+ 三版发布说明
mysql·开源·php·fengcms