后端中间件处理跨域问题 CORS

发布于 2024-06-12  25 次阅读


  /**
     * 允许跨域请求
     * @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);
}
ℳ๓古依博學之誌°ꦿ⁵²º᭄
最后更新于 2024-06-12