You need to enable JavaScript to run this app. 使用Node+https调用带Basic Auth的外部API返回401但Postman请求正常求助
优惠活动
大模型
产品
解决方案
定价
更多

使用Node+https调用带Basic Auth的外部API返回401但Postman请求正常求助

问题解决方案

核心问题原因

Node.js 原生 https 模块的 get 方法参数格式不符合要求:第二个参数是完整的请求配置对象,请求头必须放置在配置对象的 headers 字段下,你直接将仅包含 Authorization 字段的对象作为第二个参数传入,模块无法识别为请求头,导致实际发出的请求没有携带身份校验信息,因此返回401状态码。

修正代码

把调用https.get的部分修改为以下内容即可:

https.get(url, {
  headers: auth
}, (response) => {
  // 原有逻辑保持不变
  console.log(response.statusCode);
  console.log(auth);
  response.responseType="text";
  response.on("data", (data)=> {
      const translationLot = JSON.parse(data)
      console.log(translationLot);
  })
// 建议新增错误监听,避免请求异常无提示
}).on('error', (err) => {
  console.error('请求出错:', err)
})

额外排查建议

  • 如果修改后仍然报错,可以打印实际发出的请求配置,确认Authorization头是否正常携带
  • 确认basic-authorization-header库生成的凭证串和Postman中生成的是否一致,排除凭证生成错误的可能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 12:36:04