方法一:

直接在函数的开头添加 header(‘Access-Control-Allow-Origin: *’);
这个方法不需要使用官方中间件

public function getData(){
header('Access-Control-Allow-Origin: *');
$db = new Data();
$select = $db->select();
$select = $select->toArray();
return json($select);
}

方法二:

在入口文件加入这个就可以跨域请求了

header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods:GET, POST, OPTIONS, DELETE");
header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding");

路径:\public\index.php

tp6/5 API接口 允许跨域请求 header(“Access-Control-Allow-Origin:*“);_php