Sign in
Log inSign up

Post hidden from Hashnode

Posts can be hidden from Hashnode network for various reasons. Contact the moderators for more details.

They show me a error Error: cannot read property '0' of undefined internal server error i dont know why please what should i do ?

Default profile photo
Anonymous
·Nov 4, 2019

//@Route POST/api/admin/login //@Descp admin login //@Access Private router.post('/login', async(req,res) => {

// return res.send ({ message: 'ok'})
    //destructure adminUsername & Password
    let {adminUsername,adminPassword} = req.body;
       // console.log(adminPassword);
    //lowercase adminUsername
    adminUsername = adminUsername.toLowerCase();

    try {
        //validate api params
        const {error} = apiParamsForValidate.schema({adminUsername,adminPassword});
         // console.log(adminPassword);
            if(error){
                return res.status(400).json({
                    success: false,
                    message: error.details[0].message
                });
            }

         // find admin into the database
         const user = await User.findOne({adminUsername});
       //   console.log(adminUsername);
             if(!user){
                 return res.status(400).json({
                    success: false,
                    message: "please provide authenticate admin & password"
                 });
             }

          // compare password
    const isMatch = await bcrypt.compare(adminPassword, user.adminPassword);
  //  console.log(adminUsername);
    if (!isMatch) {
        return res.status(400).json({
            success: false,
            message: "Invalid adminPassword"
        });
    }

    // create jsonwebtoken
    const payload = {
        user: {
            adminUsername: user.adminUsername,
            id: user._id
        }
    };

    const token = await jwt.sign(payload, JWT_SECRET, {
        expiresIn: "365d"
    });

    // send response
    return res.json({
        success: true,
        token,
        adminUsername: user.adminUsername,
        _id: user._id
    });    

    } catch(error){
        console.log('Error:', error.message);
        res.status(500).json({
        message: "Internal server error",
        success: false,
        error: error.message
    });
 } 

});