How to exit the condition loop in this register with Mongoose/Express

Asked

Viewed 51 times

-1

I was learning how to connect my API to a database using Mongodb, so I started learning how to register users and everything was going fine until I got caught up in a problem that’s keeping me from moving forward, because I’m not sure how to handle it.

I have my API running normally, connects to the Mongodb Atlas database without any error, the problem is that when I run these lines of code:

``router.post('/create', (req, res) => { const {email, password} = req.body;

if(!email || !password) return res.send({ error: 'Dados Insuficientes!' });

Users.findOne({email}, (err, data) => {
    if (err)  return res.send({ error: 'Erro ao buscar usuário!' });
    if (data) return res.send({ error: 'usuário já registrado!'});

    Users.create(req.body, (err, data) => {
        if (err) return res.send({error: 'Erro ao criar o usuário!'});

        return res.send(data);
    })
})

}) ``

It always stops at the repeat loop of the first if of which it is:

if(!email || !password) return res.send({ error: 'Dados Insuficientes!' });

Mostrando que passo pelo body os dados que ele precisa para continuar rodando e ele me retornando esta mensagem de erro do qual está neste laço de condição

Even if I populate with data that need, in this case, email and password, it always falls in this condition saying that it does not have such data. What should I do to make the code run without falling into this condition even if it exists? That is, to be able to register my user.

3 answers

1

Check if you have configured express to receive data in JSON format, and if POSTMAN is sending the data in JSON format, if it is all right with this, debug or use the console to check that the body is not empty.

0

Tries to assign separately:

    router.post('/create', (req, res) => {
    const email = req.body.email;
    const password = req.body.password;
    
    if(!email || !password)
res.send({ error: 'Dados Insuficientes!' })

You also don’t need Return in Response.

  • Unfortunately still remains in the condition loop.

0


Actually I think the problem is in Postman, the body type of the request is text and should be Json

Browser other questions tagged

You are not signed in. Login or sign up in order to post.