简体   繁体   中英

How to get session variable in app.post request?

I would like to get the data from session variable (req.user.username) then use it for posting. I'm using passportjs as authentication. I'm using router. Here is my code:

router.use('/login', passport.authenticate("local-register", async (err, user, info) => {
      if (err) {
        return next('Error');
      }
      if (!user) {
        return next('Error'); 
      }
      req.user = user;
      return req.login(user, (error: Error) => {
        if (error) {
          return next('Error');
        }
        return req.session.save((erro: Error) => {
          if (erro) {
            return next('Error');
          }
          return next();
        });
      });
    })(req, res, next);)
router.get('/', async (req, res) => {
  console.log(req.user.username) // working just fine
});
router.post('/upload', async (req, res) => {
  const uploaderName = req.user.username // I'm getting undefined
  const upload = await database.query('INSERT INTO user WHERE username=$1', [uploaderName])

  console.log(uploaderName);
})

So I finally found the answer to the question. For those who will encounter the problem in the future. You just add the session middleware AGAIN on the top of the routes. If your routes are separated to the main server file. /src/routes/routes.ts -> add again the middleware on top.

const app = router();
app.use(sessions) // -> right here you need to add the middleware again to //access the req.user session variable 
app.get('/', async (req, res) => {
  console.log(req.user.username) // working just fine
});
app.post('/upload', async (req, res) => {
  const uploaderName = req.user.username // I'm getting undefined
  const upload = await database.query('INSERT INTO user WHERE username=$1', [uploaderName])

  console.log(uploaderName);
})

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