Check all the requests

Asked

Viewed 75 times

1

Hello, I am using express-Session and would like to know how to verify the session of all incoming requests on the server. For example, today I’m using the stretch on all my routes:

app.get('/telemetrias', (req, res) => {
    if (!req.session.uniqueId) {
        res.redirect('/');
        return;
    }
});

That is, in each route you have this IF to verify the session. And I’d like the nodejs to check every request before directing it to the specific route.

There is no express-Session tag and I also have no score to create tags.

1 answer

1

Just create a middleware and assign it in the function app.use:

const validar = (req, res, next) => {
  if (!req.session.uniqueId) {
    res.redirect('/');
    return;
  }

  next();
};

app.use(validar);
  • Yeah. I’ve tried that, but it doesn’t work. So the application goes into a looping. And it actually makes sense that enter, because there is no session, dai directs to the route "/", dai when directs it enters again in this middleware and directs again to the route "/".

  • This project is on github: https://github.com/diegocacilha/EstacaoMeteorologic This project uses Boby-parser, express, express-Session, consign, Helmet.

  • Okay. It even works. But there is a problem, when the user tries to log in, the session still does not exist and enters again in this middleware and the user cannot log in

  • @Diegoarmandocacilha Ué, but your question said "all requests". You can rely on the answer of the question Exclude route from express middleware to get what you want

  • ah ok.. OK! I forgot to mention that the login attempt does not need to go through this middleware, because it is precisely this request that creates the Session

  • @Diegoarmandocacilha there you want a magic to find out what is and what is not.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.