在NodeJS中使用https.request和Options时连接重置

lvjbypge  于 2023-05-22  发布在  Node.js
关注(0)|答案(1)|浏览(82)

在NodeJS中,当我使用https.get()时,我的代码可以正常工作,返回所需的响应。但是,当我切换到https.request()与requestOptions,我得到连接重置错误,与以下堆栈跟踪:

err: {
  code: "ECONNRESET",
  stack: ""Error: read ECONNRESET\n    at TLSWrap.onStreamRead (node:internal/stream_base_commons:217:20)\n    at TLSWrap.callbackTrampoline (node:internal/async_hooks:130:17)"
}

代码在下面。只需交换https.get & https.request:

const express = require('express');
const axios = require('axios');
const https = require('https');
const app = express();

app.all('/api/*', (req, res) => {
  forwardRequest(req, res);
});

app.listen(4600, () => {
  console.log('Proxy server listening on port 4600');
});

function forwardRequest(req, res) {
  const agolUrl = buildTargetUrl(req);

  const requestOptions = {
    port: 443,
    method: req.method,
    headers: req.headers,
  };

  // const proxyReq = https.get(agolUrl, (proxyRes) => {
  const proxyReq = https.request(agolUrl, requestOptions, (proxyRes) => {
    let responseData = '';
    proxyRes.on('data', (chunk) => {
      responseData += chunk;
    });
    proxyRes.on('end', async () => {
      doSomethingWithResponseData(responseData);
      res.writeHead(proxyRes.statusCode, proxyRes.headers);
      res.write(responseData);
      res.end();
    });

  }).on('error', (err) => {
    console.error(err);
    res.status(500).send('An error occurred with proxy.');
  });

  req.pipe(proxyReq); // What does this do?
}

function buildTargetUrl(req) {
  let targetUrl = 'https://some-remote-server.com' + req.originalUrl;

  targetUrl = decodeURI(targetUrl);

  targetUrl = targetUrl.replace('/api', '');

  return targetUrl;
}

function doSomethingWithResponseData(responseData) {
  // Custom logic here.
}

相关性包括:

// Node version is v16.20.0
      "dependencies": {
        "axios": "^1.4.0",
        "express": "^4.18.2",
        "request": "^2.88.2"
      }

注意,这与this question相同,但不幸的是它还没有答案,所以在这里发布一个新的答案。

eeq64g8w

eeq64g8w1#

好吧,我知道了。在头文件中,目标主机“https://some-remote-server.com”不喜欢host值(在我的例子中,它是localhost)。
从header中删除host成功了。

相关问题