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

一文详解thinkphp6如何通过全局中间件解决跨域问题,第1张

一文详解thinkphp6如何通过全局中间件解决跨域问题 下面thinkphp框架教程栏目将给大家介绍thinkphp6如何通过全局中间件解决跨域问题,希望对需要的朋友有所帮助!

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

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

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

get请求:可以通过后台设置解决。
'Access-Control-Allow-Origin: *'。
post请求:会发生OPTIONS请求。在ajax请求中添加一个header头信息。
header:{
    'Content-Type':'application/x-www-form-urlencoded'
}
定义中间件
<?php
declare (strict_types = 1);

namespace app\middleware;
use think\Response;

/**
 * 全局跨域请求处理
 * Class CrossDomain
 * @package app\middleware
 */

class CrossDomain
{
    public function handle($request, \Closure $next)
    {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Max-Age: 1800');
        header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE');
        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');
        if (strtoupper($request->method()) == "OPTIONS") {
            return Response::create()->send();
        }

        return $next($request);
    }
}
在middleware.php中加入我们定义的中间件

然后跨域就好使了!

以上就是一文详解thinkphp6如何通过全局中间件解决跨域问题的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/701810.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-23
下一篇 2022-04-23

发表评论

登录后才能评论

评论列表(0条)

保存