Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

156
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda