如果我禁用NODE_TLS_REJECT_UNAUTHORIZED,我的请求仍然会被拒绝

时间:2018-07-02 12:26:20

标签: node.js fetch

我禁止Node拒绝自签名证书并发出请求。

const { USER, PW } = process.env;

const b64 = new Buffer(`${VP_API_USER}:${VP_API_PW}`).toString("base64");

const Authorization = `Basic ${b64}`;

const doFind = async url => {
  process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
  const results = await fetch(url, { headers: { Authorization } })
    .then(r => (r.ok ? r.json() : Promise.reject(r)))
    .catch(err => {
      return Promise.reject(err);
    });
  process.env.NODE_TLS_REJECT_UNAUTHORIZED = 1;

  return results;
};

我仍然被拒绝。

{ FetchError: request to https://<url>:55544/contracts failed, reason: connect ECONNREFUSED <url>:55544
    at ClientRequest.<anonymous> (/Users/mjhamm75/Developer/sedd-monorepo/node_modules/node-fetch/index.js:133:11)
    at emitOne (events.js:116:13)
    at ClientRequest.emit (events.js:211:7)
    at TLSSocket.socketErrorListener (_http_client.js:387:9)
    at emitOne (events.js:116:13)
    at TLSSocket.emit (events.js:211:7)
    at emitErrorNT (internal/streams/destroy.js:64:8)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)
  name: 'FetchError',
  message: 'request to https://<url>:55544/contracts failed, reason: connect ECONNREFUSED <url>:55544',
  type: 'system',
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED' }

我在做什么错了?

3 个答案:

答案 0 :(得分:4)

process.env.NODE_TLS_REJECT_UNAUTHORIZED = 1;

该行应放在回调内部(您或然后在返回之前捕获。因为一个承诺在回调中得到解决,但您的行

process.env.NODE_TLS_REJECT_UNAUTHORIZED = 1;

是写在它外面的,即使它出现在语句之后,它也可以立即运行而无需等待回调。因此,永远不会禁用您的tls。

我希望这会有所帮助:)

答案 1 :(得分:1)

上一个答案似乎不正确-等待推迟下一行的执行,直到承诺将被解决。 根据{{​​3}},NODE_TLS_REJECT_UNAUTHORIZED值应为字符串“ 0”以禁用TLS验证。

答案 2 :(得分:0)

如果我事后必须重置环境变量,我会这样做。

使用 .finally(),无论获取的结果如何,语句都会执行。

const doFind = async url => {
  process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
  const results = await fetch(url, { headers: { Authorization } })
    .then(r => (r.ok ? r.json() : Promise.reject(r)))
    .catch(err => {
      return Promise.reject(err);
    })
    .finally(() => {
      process.env.NODE_TLS_REJECT_UNAUTHORIZED = 1;
    });
  return results;
};