Can I send data via express next() function?

99封情书 提交于 2019-12-18 12:28:52

问题


I'm working on a webapp that requires atuhentication process and session management with express. I've done with the backend sessions stuff. Now i want to show on the UI the user who is signed in. privateContent is a function that verify if someone is logged in, Like so:

...
app.get( '/authRequired', queries.privateContent , routes.tasks );
...

Here is queries.privateContent:

...
exports.privateContent = function ( req, res, next ) {
  if ( req.session.user ) {
    var username = req.session.user.username;
    User.findOne( { 'username': username }, function ( err, obj ) {
      if ( true ) {
        next();
      } else {
        res.redirect('/');
      }
    });
  } else {
    res.redirect('/');
  }
};
...

What i want to know is: Am i able to send data like this? :

...
next( username );
...

if so, how can i retrieve it when routes.tasks render, if that happens as follows (i'm trying to get the data in the code below, but it does not work.):

...
exports.my_tasks = function ( req, res, data ) {
      console.log(data);
      res.render('tasks/tasks',
                  { title: 'Paraíso', controller: 'MyTasksController', user: data });
};
...

As you can guess, my intentions are to pass via next the current user who is signed in to the routing modules, so i can print the username in the UI using jade. Thank you for your help. :)


回答1:


In this case you have a few options (only use one of these!):

  1. You can just access the req.session.user.username variable from your my_tasks route
  2. You can use res.locals
  3. You can add data to the req object

In your exports.privateContent function, once a user is found in the database, you can simply add that data to the res.locals:

User.findOne( { 'username': username }, function ( err, obj ) {
  if ( true ) {
    // this variable will be available directly by the view
    res.locals.user = obj;

    // this will be added to the request object
    req.user = obj;

    next();
  } else {
    res.redirect('/');
  }
});

Then in your exports.my_tasks route, res.locals.user will be whatever obj was in the middleware. You can then simply access that in the view as the variable user.

So, all together, you can access the data in your route in these ways:

exports.my_tasks = function ( req, res ) {
   res.render('tasks/tasks', {
     userFromReq: req.user, // this exists because you added in the middleware
     userFromSession: req.session.user, // this was already in the session, so you can access
     userFromRes: [DO NOT NEED TO DO THIS] // because res.locals are sent straight to the view (Jade).
   });
};


来源:https://stackoverflow.com/questions/19793723/can-i-send-data-via-express-next-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!