I am new to Node JS. I am practising to build a MERN app. I have two function getUserById and isSignedIn. These two function are middlewares.
router.param("userId",getUserById)
const getUserById = (req,res,next,id)=>{
User.findById(id).exec((err,user)=>{
if(err){
return res.json({
error:"Unable to process request",
status: false,
})
}
console.log(1234);
if(!user){
return res.json({
error:"User doesn't exist",
status: false
})
}
req.user=user;
next()
})
}
const isSignedIn = (req,res,next)=>{
const token = req.headers.authorization.split(" ")[1]
jwt.verify(token, process.env.SECRET_KEY, (err, decoded)=>{
if(err){
return res.json({
status: false,
error: "Invalid Token"
})
}
console.log(123);
req.auth=decoded
next()
})
};
router.post("/api/create/:userId",isSignedIn,(req,res)=>{ res.send("Success")})
This is my understanding. If in url userId is found getUserById will be executed and then isSigned in. In getUserById if there was an error or if the user doesn't exist if will send a response and the execution of code stop there. But in isSignedin if the token is not valid I am sending a response as Invalid Token and the code execution should stop there. But the code after if is also getting executed why it is so?
Try following code
router.param("userId",getUserById)
const getUserById = async (req,res,next,id)=>{
try {
const user = await User.findById(id)
if(!user){
return res.json({
error:"User doesn't exist",
status: false
})
} else {
req.user=user;
next()
}
} catch (err) {
return res.json({
error:"Unable to process request",
status: false,
error: JSON.stringify(err),
})
}
}
const isSignedIn = async (req,res,next)=>{
const token = req.headers.authorization.split(" ")[1]
try {
const decoded = await jwt.verify(token, process.env.SECRET_KEY)
if (decoded) {
req.auth=decoded
next()
}
} catch (err) {
if(err){
return res.json({
status: false,
error: "Invalid Token"
})
}
}
};
router.post("/api/create/:userId",isSignedIn,(req,res)=>{ res.send("Success")})