Skip to content
Advertisement

Couldn’t generate jwt token with a nodejs sign-in

I’m trying to singin with existing user but it shows Cannot POST /api/signin. The same works with signup process and I did cross check the signin route but couldn’t find where exactly the issue occurs.

signin code:

exports.signin = (req,res) => {
    User.findOne({email:req.body.email})
    .exec((error,user) => {
        if(error) return res.status(400).json({error});
        if(user){
            if(user.authenticate(req.body.password)){
                const token = jwt.sign({_id: user._id},process.env.JWT_SECRET,{expiresIn:'1h'})
                const {firstName,lastName,email,role,fullName} = user;
                res.status(200).json({
                    token,
                    user:{
                        firstName,lastName,email,role,fullName
                    }
                })
            } else {
                return res.status(400).json({
                    message:"Invalid Password"
                })
            }
        }else{
            return res.status(400).json({
                message:"Something went wrong!"
            })
        }
    })
}

router : router.get('/signin',signin)

app: app.use('/api',authRoutes);

Tried calling postman with : localhost:2000/api/signin but dint work. The same route pattern for signup worked localhost:2000/api/signup

Advertisement

Answer

It seems like you are doing a post request while in your router you are handling a get. Change it to this :

router.post('/signin',signin)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement