首页 > 解决方案 > 节点卷曲错误“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"错误。

一天多来,我一直试图让它工作并在线搜索解决方案。有谁知道这里发生了什么?为什么它在命令提示符下有效,但在节点中无效?谢谢!

标签: node.jscurl

解决方案


对于无法使用 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));

推荐阅读