您的位置 首页 php

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

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

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

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

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

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

'Access-Control-Allow-Origin: *'。

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

header:{    'Content-Type':'application/x-www-form-urlencoded'}

定义中间件

<?phpdeclare (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中加入我们定义的中间件

3b1b887f9844d5cd8b7d740238f8460.png

然后跨域就好使了!

文章来源:智云一二三科技

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

文章地址:https://www.zhihuclub.com/24650.shtml

关于作者: 智云科技

热门文章

网站地图