zoukankan      html  css  js  c++  java
  • laravel 跨域解决方案

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

    1 php artisan make:middleware EnableCrossRequestMiddleware

    2.书写中间件内容

     1 <?php
     2 namespace AppHttpMiddleware;
     3 use Closure;
     4 class EnableCrossRequestMiddleware{
     5     /**
     6      * Handle an incoming request.
     7      *
     8      * @param  IlluminateHttpRequest $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     AppHttpMiddlewareEnableCrossRequestMiddleware::class,
    4 ];

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

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

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

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

  • 相关阅读:
    在做城市选择界面时,获取首字母并转化为大写,发现好多网上的代码,个别汉字不能转为拼音(漯河、鄢陵等)
    微信小程序之开发的坑
    前端学习之学习网站
    前端学习之Angular cli
    前端学习之npm国内镜像cnpm和yarn的快速安装
    eclipse Team之pull操作从GitLab上更新项目到本地
    前端学习之angular项目的本地运行步骤
    前端学习之vscode脚本禁用的问题
    maven项目启动提示:启动过滤器异常
    前端学习之Node.js安装及环境配置
  • 原文地址:https://www.cnblogs.com/clubs/p/11738711.html
Copyright © 2011-2022 走看看