How the data is returning the id of the user

Viewed 19

This is the middleware,

const jwt = require('jsonwebtoken');
const JWT_SECRET = 'ankitis$ofaperson'

const fetchUser = (req, res, next) => {

    const token = req.header('auth-token');
    if (!token) {
        res.status(401).send({ error: "some error here 401 -  in middleware " });
    }
    try {
        const data = jwt.verify(token, JWT_SECRET);
        console.log(data  ,  "\n");
        console.log(token , "  - and  -  " , JWT_SECRET);
        req.user = data;
        next();
    }
    catch (error) {
        res.send({ error: "some error!! in middleware" })
    }
}
module.exports = fetchUser;

This is the section where the middleware is used

router.post('/getuser', fetchUser, async (req, res) => {
  try {
    let userID = req.user; 
    const user = await User.findById(userID).select("-password");
    res.send(user); 
  }
  catch {
    res.status(500).send("Internal server error  - in 3rd router");
  }
}
)

I am confused that how the data in the middleware is giving the id in the console and what this verify function is exactly doing, what I know is it verifies the JWT_SECRET key and on verifying, it is giving the value to data, from where it is getting the id of the input in the database? and what exactly is the whole line of "verify" doing?? Let me clear you up if you are not.

0 Answers
Related