Laravel跨域解决方案

编程

  1. 新建一个中间件
    phpartisanmake:middlewareEnableCrossRequestMiddleware
  2. 书写中间件内容
     

    1.  

      <?php

    2.  

      namespaceAppHttpMiddleware;

    3.  

      useClosure;

    4.  

      classEnableCrossRequestMiddleware

    5.  

      {

    6.  

      /**

    7.  

      * Handle an incoming request.

    8.  

      *

    9.  

      * @param IlluminateHttpRequest $request

    10.  

      * @param Closure $next

    11.  

      * @return mixed

    12.  

      */

    13.  

      publicfunctionhandle($request, Closure $next)

    14.  

      {

    15.  

      $response = $next($request);

    16.  

      $origin = $request->server("HTTP_ORIGIN") ? $request->server("HTTP_ORIGIN") : "";

    17.  

      $allow_origin = [

    18.  

      "http://localhost:8000",

    19.  

      ];

    20.  

      if (in_array($origin, $allow_origin)) {

    21.  

      $response->header("Access-Control-Allow-Origin", $origin);

    22.  

      $response->header("Access-Control-Allow-Headers", "Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN");

    23.  

      $response->header("Access-Control-Expose-Headers", "Authorization, authenticated");

    24.  

      $response->header("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, OPTIONS");

    25.  

      $response->header("Access-Control-Allow-Credentials", "true");

    26.  

      }

    27.  

      return $response;

    28.  

      }

    29.  

      }

    $allow_origin 数组变量就是你允许跨域的列表了,可自行修改。

  3. 然后在内核文件注册该中间件
     

    1.  

      protected $middleware = [

    2.  

      // more

    3.  

      AppHttpMiddlewareEnableCrossRequestMiddleware::class,

    4.  

      ];

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

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

以上是 Laravel跨域解决方案 的全部内容, 来源链接: utcz.com/z/513362.html

回到顶部