详解thinkphp6如何通过全局中间件解决跨域问题

 5994

下面给大家介绍thinkphp6如何通过全局中间件解决跨域问题,希望对需要的朋友有所帮助!


tp6 通过全局中间件 解决跨域问题

tp6官网有提供跨域决绝方法,当我直接使用无法用。(可能我用的姿势不对)。

前端在Hbuildert中发送ajax请求,发生跨域。

get请求:可以通过后台设置解决。

  1. 'Access-Control-Allow-Origin: *'

post请求:会发生OPTIONS请求。在ajax请求中添加一个header头信息。

  1. header:{
  2.     'Content-Type':'application/x-www-form-urlencoded'
  3. }

定义中间件

  1. <?php
  2. declare (strict_types = 1);
  3.  
  4. namespace app\middleware;
  5. use think\Response;
  6.  
  7. /**
  8.  * 全局跨域请求处理
  9.  * Class CrossDomain
  10.  * @package app\middleware
  11.  */
  12.  
  13. class CrossDomain
  14. {
  15.     public function handle($request, \Closure $next)
  16.     {
  17.         header('Access-Control-Allow-Origin: *');
  18.         header('Access-Control-Max-Age: 1800');
  19.         header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE');
  20.         header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With, Token');
  21.         if (strtoupper($request->method()) == "OPTIONS") {
  22.             return Response::create()->send();
  23.         }
  24.  
  25.         return $next($request);
  26.     }
  27. }


在middleware.php中加入我们定义的中间件


详解thinkphp6如何通过全局中间件解决跨域问题


然后跨域就好使了!

本文网址:https://www.zztuku.com/detail-9272.html
站长图库 - 详解thinkphp6如何通过全局中间件解决跨域问题
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐