Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
Why is this user id not coming out of req.user;

This is my code for getting user info

router.post("/getuser", fetchuser, async (req, res) => {
  try {
    userId = req.user.id;
    const user = await User.findById(userId).select("-password");
    res.send(user);
  } catch (error) {
    console.error(error.message);
    res.status(500).send("Internal Server Error");
  }
});

and this is the code for middleware fetchuser

const fetchuser = async (req, res, next) => {
const token = req.header('auth-token');
if (!token) {
    res.status(401).send({ error: "Please authenticate using a valid token" })
}
try {
    const data = jwt.verify(token, process.env.SECRET);
    console.log(data);
    req.user = data.user;
    next();
} catch (error) {
    res.status(401).send({ error: "Please authenticate using a valid token" })
}
};

I am getting the user id in console.log but when I try to get the user id in the router.post then I am not able to get the user Info. Here is the result I am getting.

Server is running on port 5000
Connected to database
{ id: '61e98c45a9d8818292b38505', iat: 1642743501 }
Cannot read properties of undefined (reading 'id')

Please can anyone tell me what is wrong with this?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

    router.post("/getuser", fetchuser, async (req, res) => {
  try {
    const params = JSON.parse(req)
    userId = params.id;
    const user = await User.findById(userId).select("-password");
    res.send(user);
  } catch (error) {
    console.error(error.message);
    res.status(500).send("Internal Server Error");
  }
});
about 4 years ago · Juan Pablo Isaza Relatório

0

Your code is working fine , you just have to change this line on fetchuser middleware

req.user = data.user

to

req.user = data

and your code work as expected..

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda