My middle tear code is not giving expected output
const verifyJWT = (req, res, next) => {
// console.log('jwt');
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).send({ message: "Unauthotized access!" });
}
const token = authHeader.split(" ")[1];
console.log(token)
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, function (err, decoded) {
if (err) {
return res.status(403).send({ message: "Forbidden access!" });
}
// console.log(decoded);
req.decoded = decoded;
// console.log(req.decoded.email, "decod");
next();
console.log('decoded',req.decoded);
});
};
Below lines of code gives the token properly const token = authHeader.split(" ")[1]; console.log(token)
But Decoding is not working properly. It's provide error and not decoding. It
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, function (err, decoded) {
if (err) {
return res.status(403).send({ message: "Forbidden access!" });
}
// console.log(decoded);
req.decoded = decoded;
// console.log(req.decoded.email, "decod");
next();
console.log('decoded',req.decoded);
});
console.log('decoded',req.decoded); gives output decoded { email: '[object Object]', iat: 1655887103, exp: 1655890703 }
CodePudding user response:
You have to assign string to the email. Debug the method that creates jwt token. Here is my method:
import jwt from 'jsonwebtoken'
const generateJwtToken = (email:string): string => {
const token = jwt.sign({ email: email }, jwtKey)
return token
}
CodePudding user response:
useEffect(()=>{
const email = user?.user?.email;
const currentUser = {email:email};
console.log(currentUser,'hfghfh')
if(email){
fetch(`http://localhost:5000/user/${currentUser.email}`,{
method: 'PUT',
headers: {
'content-type': 'application/json'
},
body:JSON.stringify(currentUser)
})
.then(res=>res.json())
.then(data=>{
console.log(data);
const accessToken = data.token;
localStorage.setItem('accessToken',accessToken);
setToken(accessToken);
})
}
},[user])
In my frontend code I made a mistake. I am passing and object thorough email and didn't extract the email value. Insepect of passing currentUser.email fetch(http://localhost:5000/user/${currentUser.email}
I was passing just currentUser.
Thanks everyone for helping me for this problem.