Fede E.
Fede E.

Reputation: 1918

NodeJS route with API request in it error

I am writing a route that checks if a system app is online and then responds to the client with a simple 200 status ok, or a 404 status.

I'm using express and request to make the api call.

Route looks like this:

app.get('/status/keymgr', async (req, res, next) => {
        try{
            var endpoint = `http://${config.KeyManager.host}:${config.KeyManager.adminPort}/healthcheck`;
            console.log(endpoint);
            await request.get(endpoint, function(err, response, body){
                if (!err && response.statusCode == 200){
                    res.send('OK');
                }else{
                    res.status(404);
                }
            }).end();
        }catch(error){
            res.status(404);
        }finally{
            next();
        }
    });

For some reason, I am getting the following error:

uncaughtException: Can't set headers after they are sent.

I am guessing some kind of response is being sent to the browser before the route runs the res.send() or the res.status().

I can't figure out what's wrong here. Any idea??

Upvotes: 0

Views: 43

Answers (1)

AbhinavD
AbhinavD

Reputation: 7292

AS @ndugger mentioned, the reason you are getting this exception is because request.get does not return a promise and hence await here is of no use. You have two options, either you use util.promisify or wrap your request under a new promise and resolve only when the callback finishes. Something like this

app.get('/status/keymgr', async (req, res, next) => {
  var endpoint = `http://${config.KeyManager.host}:${config.KeyManager.adminPort}/healthcheck`;
  console.log(endpoint);
  try {
    await new Promise((resolve, reject) => {
      request.get(endpoint, function (err, response, body) {
        if (!err && response.statusCode == 200) {
          // res.send('OK');
          resolve('OK');
        } else {
          reject('404')
          // res.status(404);
        }
      });
    });
    res.send('OK');
  } catch (err) {
    res.status(404);
  } finally {
    next();
  }
}

Upvotes: 1

Related Questions