You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node Fetch实现与Deno、Bun存在差异,无法获取高校登录页响应?

解决Deno/Bun无法获取UVIC登录页HTML的问题

问题描述

尝试获取高校登录页(https://www.uvic.ca/cas/login)的HTML内容时,Node 18内置的fetch可正常返回响应,但最新版本的Deno和Bun均失败:Deno抛出EOF错误,Bun无任何输出。Python、Golang、wget及Node均能成功获取,推测是服务器提前关闭连接,寻求解决办法。

测试代码如下:

const r = await fetch(url, {redirect: "follow"});
console.log(await r.text())

可行解决思路

  • 添加自定义User-Agent头
    部分服务器会针对Deno/Bun的默认UA做拦截,给请求添加主流浏览器或Node的UA标识:

    const url = "https://www.uvic.ca/cas/login";
    const r = await fetch(url, {
      redirect: "follow",
      headers: {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"
      }
    });
    console.log(await r.text());
    
  • 强制使用HTTP/1.1协议
    Deno/Bun默认可能启用HTTP/2,部分老服务器对HTTP/2兼容性不佳,可强制降级协议:

    • Deno:启动时添加--no-http2参数禁用HTTP/2,或手动构建HTTP/1.1请求
    • Bun:在fetch选项中添加httpVersion: "1.1"(部分版本支持,若无效可使用Bun的HttpClient手动配置)
  • 分块读取响应内容
    服务器提前关闭连接可能导致一次性读取整个响应失败,改为分块读取:

    const url = "https://www.uvic.ca/cas/login";
    const r = await fetch(url, {redirect: "follow"});
    const reader = r.body.getReader();
    let htmlContent = "";
    const decoder = new TextDecoder();
    
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      htmlContent += decoder.decode(value);
    }
    
    console.log(htmlContent);
    
  • 禁用Deno的HTTP/2多路复用
    启动Deno时添加--no-http2参数,强制使用HTTP/1.1,避免HTTP/2相关的连接问题。

内容的提问来源于stack exchange,提问作者user12957229

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 19:27:12