简体   繁体   中英

How to use a cookie with nodejs and mongodb?

I am using nodejs (express) with mongodb and I am trying to figure out how cookies work. I am currently able to let a user login and authenticate it. How do I bring cookies into play and how do I use cookies to query mongodb for the user's info to pull it onto the next page and pages after that, once they login.

Currently I have a route file that posts the login request and then redirects based on success to a userProfile page, I want to include user specific details on that page and then be able to show user other pages and have him return to his unique pages again while querying.

UPDATED CODE: (Can cookie be called the way it is called in the updated code?)

login post route file

exports.loginPost = function(req, res, next) {
    passport.authenticate('local', function(err, user, info) {
        if (err) { return next(err) }
        if (!user) { return res.redirect('loginError'); }
        req.logIn(user, function(err) {
          if (err) { return next(err); }    
          res.cookie('name', req.params.email, { expires: new Date(Date.now() + 900000), httpOnly: true });    
          return res.redirect('userProfile');
        });
  })(req, res, next);
};

read this first What does middleware and app.use actually mean in Expressjs?

then use cookieparser and cookiesession

app.use(express.cookieParser('yoursecretkeyhere'));
app.use(express.cookieSession();

and split your above function into an authentication middleware method and an authenticate POST handler.

Your authentication middleware just needs to check whether the session has an Authenticated flag and if not redirect to your login page. (if this is part of a single page app, just return a 401 and ask for credentials in your browser)

Your authenticate POST handler then checks the posted username and password credentials (or other credentials against a 3rd party api) and sets the session.Authenticated flag followed by a redirect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM