首页 > 其他 > 详细

laravel 跨域解决方案

时间:2020-09-25 16:36:07      阅读:42      评论:0      收藏:0      [点我收藏+]

 

我们在用 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 跨域解决方案

原文:https://www.cnblogs.com/guiyishanren/p/13730199.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!