Node.js内置Fetch、Axios授权请求失败,仅node-fetch正常
Node.js请求亚马逊云服务授权接口:仅node-fetch正常的问题排查
问题场景
我在亚马逊云服务器部署了应用,需在Node.js项目中实现授权功能,但不同请求方式出现了不同结果:
1. 内置Fetch API代码及错误
代码:
async function Login() { try { const response = await fetch("https://xx.xxx.xx.xx:XXXXX/auth/login", { method: 'POST', headers: { "Content-Type": "application/json; charset=utf-8" }, body: JSON.stringify({ email: "", password: "", }) }); if (!response.ok) { throw new Error(`Error! status: ${response.status}`); } console.log(await response.json()) const result = await response.json(); return result; } catch (err) { console.log(err); } }
错误信息:
TypeError: fetch failed at Object.processResponse (node:internal/deps/undici/undici:5536:34) at node:internal/deps/undici/undici:5858:42 at node:internal/process/task_queues:140:7 at AsyncResource.runInAsyncScope (node:async_hooks:202:9) at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8) { cause: Error: bad port at makeNetworkError (node:internal/deps/undici/undici:4664:51) at mainFetch (node:internal/deps/undici/undici:5677:20) at fetching (node:internal/deps/undici/undici:5664:7) at Agent.fetch2 (node:internal/deps/undici/undici:5547:20) at Object.fetch (node:internal/deps/undici/undici:6332:20) at fetch (node:internal/bootstrap/pre_execution:196:25) at getUser (file:///C:/project/auth/main.js:127:32) at file:///C:/project/auth/main.js:154:1 at ModuleJob.run (node:internal/modules/esm/module_job:198:25) at async Promise.all (index 0) { [cause]: undefined } } (node:12956) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time (Use `node --trace-warnings ...` to show where the warning was created)
2. node-fetch代码(正常运行)
import fetch from "node-fetch" async function Login() { try { const response = await fetch("https://xx.xxx.xx.xx:XXXXX/auth/login", { method: 'POST', headers: { "Content-Type": "application/json; charset=utf-8" }, body: JSON.stringify({ email: "", password: "", }) }); if (!response.ok) { throw new Error(`Error! status: ${response.status}`); } console.log(await response.json()) const result = await response.json(); return result; } catch (err) { console.log(err); } }
3. Axios代码及错误
代码:
async function Login() { return await axios.post("https://xx.xxx.xx.xx:XXXXX/auth/login", { headers: { "Content-Type": "application/json; charset=utf-8" }, withCredentials: true, body: JSON.stringify({ email: "", password: "" }) }) }
错误信息:
node:internal/process/esm_loader:91 internalBinding('errors').triggerUncaughtException( ^ AxiosError: connect EACCES xx.xxx.xx.xx:XXXXX
问题分析与解决
1. 内置Fetch API的错误原因
- 核心错误是
bad port:Node.js内置Fetch基于Undici实现,Undici严格遵循TCP/UDP端口范围(0-65535)校验端口,若你的XXXXX超出这个范围,会直接判定为无效端口;而node-fetch的端口解析逻辑更宽松,能兼容这类非标准配置。 - 内置Fetch目前是实验特性,Undici的网络请求处理逻辑仍存在边缘场景兼容性问题,比如IP+端口的HTTPS请求处理和成熟库有差异。
2. Axios的错误原因
- 参数写法错误:Axios的
post方法参数顺序为url, data, config,你把请求体数据和配置项(headers、withCredentials)混在了第二个参数里,导致请求格式异常,触发connect EACCES权限错误。 - 修正后的Axios代码:
async function Login() { return await axios.post( "https://xx.xxx.xx.xx:XXXXX/auth/login", // 第二个参数是请求体数据(无需手动JSON序列化,Axios会自动处理) { email: "", password: "" }, // 第三个参数是配置项 { headers: { "Content-Type": "application/json; charset=utf-8" }, withCredentials: true } ) }
3. 为什么只有node-fetch能正常工作
node-fetch是经过长期迭代的成熟第三方库:
- 端口解析逻辑更灵活,能兼容非标准端口配置或格式问题;
- 底层网络实现和内置Fetch(Undici)不同,对IP+端口的HTTPS请求处理更稳定;
- 无实验特性限制,兼容性覆盖更多场景。
内容的提问来源于stack exchange,提问作者alex
相关产品推荐
相关产品推荐

