Trying to get the user details by id from the mongodb server which i have created but the id is undefined.
//get user details from mongodb server
router.post("/getuser", fetchuser, async (req, res) => {
try {
const userId = req.user.id;
const user = await User.findById(userId).select("-password");
res.json(user);
} catch (error) {
console.error(error.message);
res.status(500).send("Internal Server Error");
}
});
module.exports = router;
//fetchuser middleware code
var jwt = require('jsonwebtoken');
const JWT_SECRET = '';
const fetchuser = (req, res, next) => {
// Get the user from the jwt token and add id to req object
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, JWT_SECRET);
req.user = data.user;
next();
} catch (error) {
res.status(401).send({ error: "Please authenticate using a valid token" })
}
}
module.exports = fetchuser;
I want a fix for the undefined id link to the project uploaded in github https://github.com/nirmalyax/notebook-backend
[Screenshot.] [1]: https://i.stack.imgur.com/PDOAM.png
Use body-parser middleware to parse incoming request bodies in JSON format (bodyParser.json()) and URL-encoded data (bodyParser.urlencoded()). Install body-parser via npm if you haven't :
Then, use it in your Express application like this: