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

Next.js 14 App目录中Fetch API加可选参数后报错求助

Next.js fetch添加method参数后触发ECONNREFUSED错误

现象

在app/item/page.tsx中运行以下代码时可正常获取响应:

export default async function Page() {
    const res = await fetch('http://www.testdomain.test:8000/testapi/items/');
    items = await res.json();
    console.log(items);
}

但为fetch添加method: 'GET'参数后,请求失败并抛出连接拒绝错误:

export default async function Page() {
    const res = await fetch('http://www.testdomain.test:8000/testapi/items/', {
                method: 'GET'
        });
    items = await res.json();
    console.log(items);
}

错误信息

Internal error: TypeError: fetch failed
at Object.fetch (node:internal/deps/undici/undici:11576:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Cause: Error: connect ECONNREFUSED 127.0.0.1:8000
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1495:16)
at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 8000
}
⨯ Internal error: TypeError: fetch failed
at Object.fetch (node:internal/deps/undici/undici:11576:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

环境配置

  • Windows 11 + WSL2 Ubuntu 22.04
  • 前端、后端API均运行在本地Docker容器中
  • 后端容器映射端口8000到宿主机
  • 前端容器映射端口3000到宿主机
  • Windows系统C:\Windows\System32\drivers\etc\hosts配置:
127.0.0.1 testdomain.test
127.0.0.1 www.testdomain.test 

解决方案

1. 修复Docker容器间的网络访问

Windows hosts配置仅对Windows宿主机生效,WSL和Docker容器无法直接读取该配置。显式指定method后,fetch跳过缓存重新解析域名,导致容器内无法找到后端地址:

  • 用Docker服务名访问:如果使用Docker Compose,将请求地址改为后端服务名(例如http://backend:8000/testapi/items/),容器间可通过服务名直接通信。
  • 在WSL中配置hosts:编辑WSL Ubuntu的/etc/hosts,添加域名映射到WSL宿主机IP(通过cat /etc/resolv.conf | grep nameserver获取该IP):
    172.17.0.1 testdomain.test
    172.17.0.1 www.testdomain.test
    
  • 直接使用宿主机IP:将请求地址替换为WSL宿主机IP(如172.17.0.1),绕过域名解析问题:
    export default async function Page() {
        const res = await fetch('http://172.17.0.1:8000/testapi/items/', {
                    method: 'GET'
            });
        items = await res.json();
        console.log(items);
    }
    

2. 对齐fetch默认缓存策略

不指定method时,Next.js服务器组件的fetch默认使用force-cache策略,可能复用了成功连接的缓存。显式指定method后缓存策略变化,可手动设置cache: 'force-cache'保持一致:

export default async function Page() {
    const res = await fetch('http://www.testdomain.test:8000/testapi/items/', {
                method: 'GET',
                cache: 'force-cache'
        });
    items = await res.json();
    console.log(items);
}

3. 检查后端容器端口绑定

确保后端容器的8000端口绑定到0.0.0.0而非127.0.0.1,否则仅能在容器内部访问,外部(包括前端容器)无法连接。修改后端Dockerfile或启动命令中的端口绑定配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 06:55:12