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

image.png

然后跨域就好使了!


你的名字
15 声望0 粉丝

要想得到你从未拥用过的东西,就要去做你从未做过的事。