header('origin', ''); // 允许的域名列表(根据实际情况修改) $allowedDomains = [ 'http://localhost:3000', 'http://localhost:8000', 'http://127.0.0.1:3000', 'http://127.0.0.1:8000', 'http://backapi.yunzer.cn', 'http://localhost:5173', 'http://www.yunzer.cn', 'https://www.yunzer.cn', 'http://yunzer.cn', 'https://yunzer.cn', ]; // 检查是否为允许的域名 if (in_array($origin, $allowedDomains)) { $header['Access-Control-Allow-Origin'] = $origin; } else { // 对于同源请求,允许当前域名 if (!empty($origin)) { $header['Access-Control-Allow-Origin'] = $origin; } else { $header['Access-Control-Allow-Origin'] = '*'; } } // 处理 OPTIONS 预检请求,直接返回 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'; \think\facade\Log::record('CORS OPTIONS preflight for: ' . $origin); 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'; return $next($request)->header($header); } }