Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

246
Visualizações
NodeJS: function not returning res.json

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?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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 : xyz@gmail.com

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')})

about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda