node.js - 节点卷曲错误“CONNECT 后从代理收到 HTTP 代码 503”
问题描述
在使用 POST 请求对 API 进行身份验证后,我得到了一个 JWT 令牌。
使用该令牌,我可以curl
从命令提示符成功调用:
curl --request GET https://corpURL/customer/wlsAccountManagement/v1/billingAccount/23435657 --header "env: it04" --header "Authorization: Bearer tokenstring..."
但是当我尝试在节点中执行它时,它会失败并显示Received HTTP code 503 from proxy after CONNECT
.
我什至在命令提示符下尝试了一个基本的 curl 并且它有效:
curl -v https://corpURL/customer/wlsAccountManagement/v1/billingAccount/23435657
它只是告诉我我未经授权{"message":"Unauthorized"}
,这是正确的。
在节点中,我什至无法得到{"message":"Unauthorized"}
,它仍然给了我Received HTTP code 503 from proxy after CONNECT
.
我使用 curl 的原因是因为我可以看到更多信息。使用axios
它会给我一个"socket hang up"
错误。
一天多来,我一直试图让它工作并在线搜索解决方案。有谁知道这里发生了什么?为什么它在命令提示符下有效,但在节点中无效?谢谢!
解决方案
对于无法使用 curl 的 exec 在 node 中工作或使用包 axios 或 request 的任何人,请在 node 中使用 https 包,如下所示:
const options = {
hostname: 'hostDomain', // no https protocol
port: 443,
path: '/path/to/get',
method: 'GET',
headers: {
Authorization: `Bearer tokenString`,
'Content-Type': 'application/json',
},
};
const req = https.request(options, response => {
response.on('data', d => {
process.stdout.write(d);
});
});
req.on('error', e => {
console.error(e);
});
req.end();
到目前为止,这是我能够在 node.js 中获得响应的唯一方法。我可能会调整结构,因为它看起来不那么干净,但它有效!您可能还需要NODE_EXTRA_CA_CERTS=cert.pem
像我已经拥有的那样为您的证书文件设置环境变量。和平。
编辑
我找到了一个带有 axios 的解决方案,您需要使用 baseURL 创建实例,例如 https 请求有它:
const axiosInstance = axios.create({
baseURL: 'https://corpURL',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
env: 'it04',
},
});
axiosInstance
.get('/get/path')
.then(response => console.log('response', response.data))
.catch(err => console.log('err', err));
推荐阅读
- javascript - 为什么 JavaScript 没有为它的 switch 语句实现跳转表?
- c++ - 从 std::string 创建 OssBitString?
- r - 数据框中列的段落缩进
- javascript - 连接到 mongodb atlas 时,我可以在 nodeJS 上提供代理吗?
- algorithm - 如何使用数学归纳法证明a_k > 0的每一个k次多项式都属于theta(n^k)?
- reactjs - 加载错误页面时出现错误时的用户体验是什么?
- python - Ansible 自定义插件
- reactjs - React 组件更深层次的结构和 props
- x509certificate - Hashicorp Vault - 外部证书管理
- sass - Sass:背景位置如何在背景尺寸过大的悬停效果中工作