javascript 如何在www.example.com请求中获取会话变量app.post?

gr8qqesn  于 2022-12-02  发布在  Java
关注(0)|答案(1)|浏览(150)

我想从session变量(req.user.username)中获取数据,然后将其用于发布。我使用passportjs作为身份验证。以下是我的代码:

app.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);)
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);
})
jmo0nnb3

jmo0nnb31#

你可以这样做

app.use((req, res, next) => {
  const user = getUserFromSession(req.session);
  req.user = user;
  next();
});

在这种情况下,如果getUserFromSession()函数返回undefined,则req.user也将是undefined。
要解决这个问题,你可以确保req.user属性在之前的中间件函数中设置正确,或者你可以检查undefined并在你的/upload路由处理程序中适当地处理这种情况。例如:

app.post('/upload', async (req, res) => {
  const uploaderName = req.user ? req.user.username : null;

  if (uploaderName === null) {
    res.send('There was an error getting the username.');
    return;
  }

  const upload = await database.query('INSERT INTO user WHERE username=$1', [uploaderName]);
  console.log(uploaderName);
});

或者,如果req.user或req.user.username未定义,您可以抛出一个错误,并在一个全局错误处理中间件函数中捕获该错误。这将允许您在所有路由中以一致的方式处理错误。

app.post('/upload', async (req, res) => {
  if (!req.user || !req.user.username) {
    throw new Error('There was an error getting the username.');
  }

  const uploaderName = req.user.username;
  const upload = await database.query('INSERT INTO user WHERE username=$1', [uploaderName]);
  console.log(uploaderName);
});

app.use((err, req, res, next) => {
  res.status(500).send(err.message);
});

相关问题