Task of code : Is to delete document from DB using JWT token error : sending 500 internal error
code of Auth.js
const auth=async(req,res,next)=>{
try{
const token=req.header('Authorization').replace('Bearer ','');
const decoded=jwt.verify(token,'helloworld');
const user=await User.findOne({_id:decoded._id,'tokens.token':token});
if(!user){
throw new Error();
}
// console.log(token);
req.token=token;
req.user=user;
next();
}
catch(err){
// console.log(token);
res.status(401).send({error:"please authenticate"});
}
}
module.exports=auth;
Code To delete document (API endpoint)
router.delete('/users/me',auth,async(req,res)=>{
try{
await req.user.remove();
res.status(201).send(req.user);
}
catch(err){
console.log(err);
console.log(req.user);
res.status(500).send();
}
})
The Problem is even if I am sending incorrect JWT token it should give me {error : please authenticate}
but I am not getting this error too instead I am getting 500 internal error and same error when sending correct JWT . Even I am printing error in console ,its not showing error in console
In your API endpoint, you have to call your collection name then you need to remove with query/params id.
If you are using mongoose Like this and send id from frontend as query/params,
Model.remove({ _id: req.body.id }, function(err) {
if (!err) {
message.type = 'notification!';
} else {
message.type = 'error';
}
});
or
router.delete('/users/me/:id', auth, async(req,res) => {
try {
await Model.deleteOne({ _id: req.params.id})
res.status(201).send(req.user);
} catch(err) {
console.log(err);
res.status(500).send();
}
});
I hope if you follow this way you can solve this problem.
This is the wrong way to remove await req.user.remove();
Because, when code executes it will don't know which collection of data needs to remove.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.