【问题标题】:How to set a custom timeout on http get nodeJS如何在http get nodeJS上设置自定义超时
【发布时间】:2020-05-13 21:42:19
【问题描述】:

我找不到有关如何在 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}`);
});

【问题讨论】:

  • 粘贴您正在创建快速对象并启动服务器的代码,例如app.listen()
  • @Sohan 嘿,我已经更新了我的问题。最后,我相信这取决于我运行代码的系统,因为超时在 Windows 上约为 10 秒,但在 Linux 服务器上为 2 分钟..

标签: node.js express get request timeout


【解决方案1】:

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

// 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
});

【讨论】:

  • 是的,但我不想在我的路线上设置超时,我想在该路线中提出的请求上设置它。我想我会使用第一个解决方案并将其全局设置在我的服务器上。谢谢
猜你喜欢
  • 1970-01-01
  • 2015-05-05
  • 1970-01-01
  • 2012-09-21
  • 2019-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多