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

相关推荐
悠悠~飘19 小时前
17.PHP基础-数组
php
Q_Q51100828521 小时前
python+django/flask+vue的书城图书阅读器系统,亮点含目录章节pycharm
spring boot·python·django·flask·node.js·php
计算机科学与技术学习中1 天前
文件上传漏洞
php
emma羊羊1 天前
【PHP反序列化】css夺旗赛
开发语言·网络安全·php
Q_Q5110082851 天前
python+django/flask的图书馆管理系统vue
spring boot·python·django·flask·node.js·php
Q_Q5110082851 天前
python+django/flask的美食交流宣传系统vue
spring boot·python·pycharm·django·flask·node.js·php
m0_495562781 天前
Swift的逃逸闭包
服务器·php·swift
Elastic 中国社区官方博客1 天前
Observability:适用于 PHP 的 OpenTelemetry:EDOT PHP 加入 OpenTelemetry 项目
大数据·开发语言·人工智能·elasticsearch·搜索引擎·全文检索·php
catchadmin2 天前
用 LaraDumps 高效调试 PHP 和 Laravel
php·laravel
刘恒1234567892 天前
PHP中对于(并发/并行)相关概念
php