设置为req并在另一条路线中访问

时间:2016-08-09 03:23:09

标签: javascript node.js express

我的用户必须先登录才能访问任何路由,但为什么第二条路径res.username未定义?

router.post('/login', passport.authenticate('local'), function(req, res) {
    res.username = req.user.name;
    res.json({result:1,username:req.user.name}); //work
});

router.post('/some_other_route', function(req, res, next) {
    console.log(res.username) // undefined
})

我使用带有护照的快速会话中间件。

1 个答案:

答案 0 :(得分:0)

如果您正确使用express-session, 你应该使用req.session.username = req.user.name;

以下是链接:Here is the fiddle

<强> req.session

To store or access session data, simply use the request property req.session, which is (generally) serialized as JSON by the store, so nested objects are typically fine. For example below is a user-specific view counter:

// Use the session middleware
app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}))

// Access the session as req.session
app.get('/', function(req, res, next) {
  var sess = req.session
  if (sess.views) {
    sess.views++
    res.setHeader('Content-Type', 'text/html')
    res.write('<p>views: ' + sess.views + '</p>')
    res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>')
    res.end()
  } else {
    sess.views = 1
    res.end('welcome to the session demo. refresh!')
  }
})