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

相关推荐
ServBay11 小时前
告别面条代码,PSL 5.0 重构 PHP 性能与安全天花板
后端·php
多厘2 天前
别再手写 psr-4 了!用 Composer 隐藏魔法干掉上千行烂配置
laravel
JaguarJack3 天前
FrankenPHP 原生支持 Windows 了
后端·php·服务端
BingoGo3 天前
FrankenPHP 原生支持 Windows 了
后端·php
JaguarJack4 天前
PHP 的异步编程 该怎么选择
后端·php·服务端
BingoGo4 天前
PHP 的异步编程 该怎么选择
后端·php
JaguarJack4 天前
为什么 PHP 闭包要加 static?
后端·php·服务端
ServBay5 天前
垃圾堆里编码?真的不要怪 PHP 不行
后端·php
用户962377954486 天前
CTF 伪协议
php
BingoGo8 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php