在 NodeJS 中使用带选项的 https.request 时连接重置

编程入门 行业动态 更新时间:2024-10-03 12:30:11

在 NodeJS 中使用带<a href=https://www.elefans.com/category/jswz/34/1771047.html style=选项的 https.request 时连接重置"/>

在 NodeJS 中使用带选项的 https.request 时连接重置

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

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 = '' + 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相同但不幸的是它还没有答案,所以在这里发布一个新的。

回答如下:

好的,明白了。结果在标头中,目标主机“https://some-remote-server”不喜欢

host
值(在我的例子中,它是本地主机)。

从标题中删除

host

更多推荐

在 NodeJS 中使用带选项的 https.request 时连接重置

本文发布于:2024-05-31 03:07:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1771211.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:选项   NodeJS   request   https

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!