I've built this sign in route that creates a JWT token, but outside of the function that creates it, the token is undefined, so I'm unable to use it outside of that function.
router.post('/login', (req, res) => {
    const { errors, isValid } = validateLoginInput(req.body);
    if (!isValid) {
        return res.status(400).json(errors);
    }
    const email = req.body.email;
    const password = req.body.password;
    User.findOne({ email }).then(user => {
        if (!user) {
            return res.status(404).json({ emailnotfound: "Email not found"});
        }
    bcrypt.compare(password, user.password).then(isMatch => {
        if (isMatch) {
            const payload = {
                id: user.id,
                name: user.name
            };
            var token =jwt.sign(
                payload, 
                keys.secretOrKey, 
                { expiresIn: 31556926 },
                (err, token) => {
                    res.json({
                        success: true,
                        token: "Bearer " + token
                    });
                });
            console.log(token)
            } else {
                return res.status(400).json({ passwordincorrect: 
"Password incorrect"});
            }
        });
    });
});
When the code hits that console.log statement, it shows that the token is undefined instead of returning the token.
 
     
    