tp/app/common/middleware/AllowCrossDomain.php
2026-03-10 22:24:06 +08:00

37 lines
1.4 KiB
PHP

<?php
namespace app\common\middleware;
use think\Response;
use think\Request;
/**
* 公共跨域中间件
* 供所有应用共用
*/
class AllowCrossDomain
{
public function handle(Request $request, \Closure $next): Response
{
$origin = $request->header('origin', '');
// 允许所有来源(生产环境建议限制具体域名)
$header['Access-Control-Allow-Origin'] = $origin ?: '*';
if ($request->method() === 'OPTIONS') {
$header['Access-Control-Allow-Credentials'] = 'true';
$header['Access-Control-Max-Age'] = 1800;
$header['Access-Control-Allow-Methods'] = 'GET, POST, PATCH, PUT, DELETE, OPTIONS';
$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, X-Current-Domain';
return response('', 200, $header);
}
$header['Access-Control-Allow-Credentials'] = 'true';
$header['Access-Control-Max-Age'] = 1800;
$header['Access-Control-Allow-Methods'] = 'GET, POST, PATCH, PUT, DELETE, OPTIONS';
$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, X-Current-Domain';
return $next($request)->header($header);
}
}