Connected to Mongo Successfully Cannot read properties of undefined (reading 'id')

256 Views Asked by At

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

1

There are 1 best solutions below

0
Akeel Ahmed Qureshi On BEST ANSWER

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 :

   npm install body-parser

Then, use it in your Express application like this:

 const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const port = 3000;

//  you  can use body-parser middleware here to parse incoming request
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: true })); 



app.listen(port);