如何在 http get nodeJS 上设置自定义超时



我找不到有关如何在 NodeJS 中为给定请求设置自定义超时的文档(使用 Express(?

以下不起作用.... :

https.get("https://externalurl.com", { timeout: 1000 }, (res) => {
resp.on("timeout", () => {
console.log("Never fired");
});
});

这样做也不起作用:

https.get("https://externalurl.com", (req, res) => {
req.setTimeout(1000);
});

这样做也不起作用...

https.get("https://externalurl.com", (res) => {
})
.setTimeout(1000);

它总是在抛出错误之前等待超过 1 秒

有人可以帮忙吗?是否有"官方"方法可以为给定请求设置自定义超时?

我的完整服务器.ts

// Express server
const app = express();
const PORT = process.env.PORT || 80;
const DIST_FOLDER = join(process.cwd(), "dist/browser");
// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const {
AppServerModuleNgFactory,
LAZY_MODULE_MAP,
ngExpressEngine,
provideModuleMap
} = require("./dist/server/main");
// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
app.engine(
"html",
ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [provideModuleMap(LAZY_MODULE_MAP)]
})
);
app.set("view engine", "html");
app.set("views", DIST_FOLDER);
// Example Express Rest API endpoints
// app.get('/api/**', (req, res) => { });
// Serve static files from /browser
app.get(
"*.*",
express.static(DIST_FOLDER, {
maxAge: "1y"
})
);
// All regular routes use the Universal engine
app.get("/", (req, res) => {
res.render("index", { req });
});
app.get("/myCustomRoute", (req, res) => {
const protocol: string = req.query.myUrl.split(":")[0];
let httpProtocol;
if (protocol === "http") {
httpProtocol = require("http");
} else if (protocol === "https") {
httpProtocol = require("https");
}
try {
// THIS IS THE REQUEST I WANT TO CUSTOMIZE THE TIMEOUT
httpProtocol
.get(
`${req.query.myUrl}/custom/custom/custom/custom.php?param=${req.query.myParam}`,
{ rejectUnauthorized: false },
(myRes) => {
let data = "";
// A chunk of data has been received.
myRes.on("data", (chunk) => {
data += chunk;
});
// The whole response has been received
myRes.on("end", (resXml) => {
switch (myRes.statusCode) {
case 403:
res.status(403).send("Forbidden");
break;
case 404:
res.status(404).send("Not found");
break;
default:
res.send(data);
break;
}
});
}
)
.on("error", (err) => {
console.log(err);
res.status(500).send("custom error");
});
} catch (e) {
console.log(e);
res.status(500).send("custom error");
}
});
// Start up the Node server
app.listen(PORT, () => {
console.log(`Node Express server listening on http://localhost:${PORT}`);
});

要覆盖默认超时,您需要执行以下操作, 这对我有用,

// Start up the Node server
app.listen(PORT, () => {
console.log(`Node Express server listening on http://localhost:${PORT}`);
}).setTimeout(20000); //Time is in msecs

要设置特定路由,您需要设置响应超时而不是请求超时,您需要覆盖响应超时:

app.post('/xxx', function (req, res) {
res.setTimeout(500000); //Set response timeout
});

最新更新