/**
* 允许跨域请求
* @access public
* @param Request $request
* @param Closure $next
* @param array $header
* @return Response
*/
public function handle($request, Closure $next, ?array $header = []) {
$header = !empty($header) ? array_merge($this->header, $header) : $this->header;
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
// 获取请求的Origin头
$origin = $request->header('origin');
// 根据请求的Origin头和cookieDomain设置Access-Control-Allow-Origin
if ($origin && ('' == $this->cookieDomain || strpos($origin, $this->cookieDomain) !== false)) {
$header['Access-Control-Allow-Origin'] = $origin;
} else {
$header['Access-Control-Allow-Origin'] = '*';
}
// 设置响应状态码为204 No Content
http_response_code(204);
// 返回带有适当CORS头的响应
return $next($request)->header($header);
}
// 如果响应头中没有Access-Control-Allow-Origin,则设置该头
if (!isset($header['Access-Control-Allow-Origin'])) {
$origin = $request->header('origin');
if ($origin && ('' == $this->cookieDomain || strpos($origin, $this->cookieDomain) !== false)) {
$header['Access-Control-Allow-Origin'] = $origin;
} else {
$header['Access-Control-Allow-Origin'] = '*';
}
}
// 返回带有适当CORS头的响应
return $next($request)->header($header);
}
后端中间件处理跨域问题 CORS
发布于 2024-06-12 26 次阅读
Comments NOTHING