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

然后跨域就好使了!
立即学习“PHP免费学习笔记(深入)”;


