选项的 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 时连接重置
发布评论