Just add a middleware.php file under the api, mine is handled like this
<?php
// 全局中间件定义文件
return [
think\middleware\AllowCrossDomain::class
];
If the data return value is customized
/**
* 生成json数据返回值
*/
function XXXJsonReturn($msg, $status = -1, $data = [])
{
header('Content-Type:application/json; charset=utf-8');
header("Access-Control-Allow-Origin: *");
$rs = ['status' => $status, 'msg' => $msg];
$rs['data'] = $data;
exit(json_encode($rs, JSON_UNESCAPED_UNICODE));
}
Remember to add a header("Access-Control-Allow-Origin: *");
If the online server still doesn’t work, add it to the entry file
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization, token");
header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
file_put_contents('option.txt',json_encode($_REQUEST));
exit;
}
header('Access-Control-Allow-Origin:*');
// 响应类型
header('Access-Control-Allow-Methods:*');
// 响应头设置
header('Access-Control-Allow-Headers:content-type,token,id');
header("Access-Control-Request-Headers: Origin, X-Requested-With, content-Type, Accept, Authorization, token");