发布于:2021-05-11 21:25:41
在文件app/middleware.php加入
\think\middleware\ALLowCrossDomain::class
tp6内置的中间件middleware有点问题,请使用以下中间件
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,access-control-allow-origin,content-type,xx-devicetype,xx-secretkey,xx-softcode,xx-token'); if (strtoupper($request->method()) == "OPTIONS") { return Response::create()->send();
} return $next($request);
}
其中 Access-Control-Allow-Headers 里面xx-devicetype,xx-secretkey,xx-softcode,xx-token的参数要增加,不然会包cros错误
https://zhuanlan.zhihu.com/p/105386883
在网站根录下 index.php 下加上
// [ 应用入口文件 ]
// 处理跨域需遇见请求
if(isset($_SERVER['REQUEST_METHOD'])&&$_SERVER['REQUEST_METHOD']=='OPTIONS'){
// 允许的原域名
header('Access-Control-Allow-Origin:*');
//允许的请求头信息
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
//允许的请求类型
header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
//允许携带证书式访问(携带cookie)
header('Access-Control-Allow-Credentials:true');
exit;
}
然后再你的公共的控制器中 使用tp自带的方法_initialize 或者构造方法 这里使用的是_initialize
// 将要跨域的控制器方法 继承这个公共的控制器 即可
// 初始化方法
public function _initialize(){
parent::_initialize();
header('Access-Control-Allow-Origin:*');
//允许的请求头信息
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
//允许的请求类型
header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
//允许携带证书式访问(携带cookie)
header('Access-Control-Allow-Credentials:true');
}
阅读 1303+
10