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

Spring Boot设置server.address=localhost后Node.js fetch无法连接的原因

问题原因解析:Spring Boot配置server.address=localhost后Node.js fetch无法连接

问题现象

  • Spring Boot服务配置server.address=localhost后,Node.js的fetch API请求http://localhost:8082/api/auth/test失败,但网页浏览器访问正常;注释host文件中的::1 localhost行后,fetch也能正常连接。
  • 不配置server.address项时,fetch连接无任何问题。

错误日志

执行以下fetch代码:

fetch("http://localhost:8082/api/auth/test")
    .then(response => response.text())
    .then(data => console.log(data))
    .catch(err => console.error(err));

返回错误:

TypeError: fetch failed
    at Object.processResponse (node:internal/deps/undici/undici:6277:34)
    at node:internal/deps/undici/undici:6602:42
    at node:internal/process/task_queues:140:7
    at AsyncResource.runInAsyncScope (node:async_hooks:203:9)
    at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  cause: Error: connect ECONNREFUSED ::1:8082
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1247:16) {
    errno: -61,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '::1',
    port: 8082
  }
}

curl测试结果

使用curl http://localhost:8082/api/auth/test请求正常,输出如下:

*   Trying 127.0.0.1:8082...
* Connected to localhost (127.0.0.1) port 8082 (#0)
> GET /api/auth/test HTTP/1.1
> Host: localhost:8082
> User-Agent: curl/7.88.1
> Accept: */*
> 
< HTTP/1.1 200 
< Vary: Origin
< Vary: Access-Control-Request-Method
< Vary: Access-Control-Request-Headers
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 0
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< Content-Type: text/plain;charset=UTF-8
< Content-Length: 11
< Date: Wed, 09 Aug 2023 09:52:05 GMT
< 
* Connection #0 to host localhost left intact
test ok 123%    

核心原因

  1. 地址解析优先级差异:
    Node.js的fetch(底层基于undici库)解析localhost时,优先选择IPv6地址(::1);而curl和主流浏览器会优先尝试IPv4地址(127.0.0.1),或者会依次尝试所有解析到的地址直到连接成功。

  2. Spring Boot绑定范围不同:

    • 当配置server.address=localhost时,Spring Boot实际只绑定了IPv4的127.0.0.1(Java在多数系统环境下解析localhost为IPv4地址,且仅绑定该地址的端口),导致IPv6的::1:8082端口没有服务监听,所以Node.js用IPv6地址连接时被拒绝。
    • 不配置server.address时,Spring Boot默认绑定0.0.0.0(所有IPv4地址)和::(所有IPv6地址),不管Node.js用IPv4还是IPv6地址都能正常连接。
  3. host文件的影响:
    注释host文件中的::1 localhost行后,Node.js解析localhost只能得到IPv4的127.0.0.1,自然能连接到绑定该地址的Spring Boot服务。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 18:15:02