0

Currently I'm developing an Express app using middlewares. First step, I need to authenticate the users. In app.js I've:

app.post('/api/ecosystem/project/auth',
    middleware.authenticate,
    function(req,res){
    }
);

In the middleware, I need to access to the params provided by the user, so I access to body, setting headers. In middleware/index.js:

function authenticate(req, res, next){
        var plainPassword = req.body.password,
            userName = req.body.username;

        models.connection.query(
               `SELECT * FROM TABLE_1 WHERE username = ?`,
               [userName] ,function(err, query) {
                     var err = true; //for testing purposes
                     if (err) res.statusCode = 500;

               console.log('continues');
               //...

The problem comes when I try to send the status code turning back. As headers have been set, I can't use res.send(), res.status(), next() with an error param and so on. If I do that, I have an error about Headers have already been sent. There's a very amazing answer here about this.

So I can use just res.statusCode but this does not return the status and does not stop the flow. Also, I can't send other params as err.message in a JSON file.

Any ideas about how to solve this?

Thanks!!

Community
  • 1
  • 1
Joss
  • 535
  • 1
  • 8
  • 28

1 Answers1

1

You can store statusCode in err object and pass it to next function. If your routes are defined properly, you should have middleware for handling unprocessed errors. That handler can use err.statusCode to set correct response statusCode.

function authenticate(req, res, next){
  var plainPassword = req.body.password;
  var userName = req.body.username;

  models.connection.query(
    `SELECT * FROM TABLE_1 WHERE username = ?`,
    [userName],
    function(err, query) {
      if (err) {
        err.statusCode = 500;
        return next(err);
      }
    }
  );
});

In your routes.js you must have:

YOUR ROUTES

app.use(function(err, req, res, next) {
  res.status(err.statusCode).send(err);
});
alexmac
  • 19,087
  • 7
  • 58
  • 69