skip to Main Content

So I am making a post api for registration/signup. If a user is successfully been registered, an access token will be provided to the user for saving it in frontend.
Everything works, the username, password is saving in database along with the token. But the access token is not returning. I have used mongoDB as my database and used mongoose. Here what I have done so far:
Edited code

const UserModel = require("../models/userModel");
var bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");

const registration = async (req, res) => {
  try {
    const { email, password } = req.body;
    if (!(email && password)) {
      res.status(400).send("All input is required");
    }
    const existingEmail = await UserModel.find({ email: email });
    if (existingEmail.length === 0) {
      const userToken = jwt.sign({ email: email }, process.env.SECRET, {
        expiresIn: "90d",
      });

      let hashedPassword = await bcrypt.hash(password, 8);
      const user = await UserModel.create({
        email,
        password: hashedPassword,
        token: userToken,
      });
      await userRegistration.save(function (err, result) {
        if (err) {
          console.error(err);
        } else {
          console.log(result);
        }
      });
      res.json(userToken);
    } else {
      res.json("email has already been registered");
    }
  } catch (err) {
    res.json(err);
  }
};

module.exports = registration;

if I test the api in thunder client on vscode, it is returning {}, an empty object. Please tell me what I have done wrong?

4

Answers


  1. Chosen as BEST ANSWER

    So, I made a simple mistake in the code. I was trying to save userRegistration which was not defined. That's why the bug was occurring. I should be more careful about this.


  2. Kindly try the below mentioned code.

    const UserModel = require("../models/userModel");
    var bcrypt = require("bcryptjs");
    const jwt = require("jsonwebtoken");
    
    const registration = async (req, res) => {
      try {
        const { email, password } = req.body;
        if (!(email && password)) {
          res.status(400).send("All input is required");
        }
        const existingEmail = await UserModel.find({ email });
    
       if (existingEmail.length === 0) {
         const userToken = jwt.sign({ email }, process.env.SECRET, {
           expiresIn: "90d",
         });
    
         let hashedPassword = await bcrypt.hash(password, 8);
         const user = await UserModel.create({
           email,
           password: hashedPassword,
           token: userToken,
         });
    
         const userRegistrationResponse = await userRegistration.save();
    
         const responseObj = {
           ...userRegistrationResponse,
           accesstoken: `${userToken}`
         };
      
         res.json(responseObj);
    
    
         } else {
           res.json("email has already been registered");
         }
      } catch (err) {
        res.json(err);
      }
    };
    
    module.exports = registration;
    
    Login or Signup to reply.
  3. const existingEmail = await UserModel.find({ email }); This line of yours will provide you the array of all the users because email property has nothing, it will be just like .find({})

    If you are checking if the email inserted by user is already in your database or not, I suggest you do it like this: const existingEmail = await UserModel.find({ email : email});
    This will return the document with email property’s value equal to the email you received in req.body i.e. email : [email protected]

    And In this line const userToken = jwt.sign({ email }, process.env.SECRET, {expiresIn: "90d",});
    You are again making same mistake. The object you pass in payload, has email property, but no value/email is assigned to that property.
    It’s just like email : undefined

    Here, do it like this jwt.sign({email : email}, process.env.SECRET, {expiresIn: '90d')})

    Login or Signup to reply.
  4. Apart from what has been mentioned in the other answers, to me it looks like you are not giving the token to res.json anywhere.

    Your function is returning the token, but I dont think its going anywhere. You need to pass the token to res.json, not return from the function.

    You are using await as well as .then() which looks wrong to me. You have to use just one of them.

    Update:
    jwt.sign returns a string so userToken contains string. You are giving that string to res.json which is expecting a json. You need to pass an object to it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search