1

I can't find documentation on how to set a custom timeout for a given request in NodeJS (with Express) ?

The following isn't working .... :

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

Doing this doesn't work either :

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

Doing this doesn't work either ...

https.get("https://externalurl.com", (res) => {

})
.setTimeout(1000);

It always waits more than 1 sec before throwing an error

Can someone help ? Is there an "official" way to set a custom timeout for a given request ?

My full server.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}`);
});
Yohan Dahmani
  • 1,670
  • 21
  • 33
  • paste the code where you are creating express object and starting the server something like `app.listen() ` – Sohan Jan 29 '20 at 07:43
  • @Sohan Hey, I've updated my question. In the end I believe that it depends the system I'm running the code on, because the timeout is about 10 secs on Windows but 2 minutes on a Linux Server .. – Yohan Dahmani Jan 29 '20 at 08:31

1 Answers1

6

To override the default timeout you need to do something like this, This is working for me,

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

To set for specific route you need to set response timeout and not the request timeout, you need to override response time out:

 app.post('/xxx', function (req, res) {
   res.setTimeout(500000); //Set response timeout
});
Sohan
  • 6,252
  • 5
  • 35
  • 56
  • 1
    Yeah but I don't wanna set the timeout on my route, wanna set it on a request made in that route. I guess I'll go with the first solution and set it globally on my server. Thanks – Yohan Dahmani Jan 29 '20 at 09:57