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

258
Visualizações
Handle create instance promise inside find promise sequelize

unfortunately I can't seem to apply m understanding of promises to sequelize: On my login/authenticate route I'm trying to store my token linked to my user in my database but i'm getting the unhandled promise reection error : My method goes like this :

exports.authenticate = (req, res) => {
    const credentials = req.body;
    User.findOne({
        where : {
            email : req.body.login
        }
    })
    .then((user) => {
        if (!user) {
            console.log('notfound!')
            res.status(404).send("user not found");
        } else { 
        if (bcrypt.compareSync(req.body.password, user.password)){
            const token = jwt.sign({username : user.username}, secret.secret, {expiresIn : "2 days"});
            Token.create({
                code : token, 
                expired_at : sequelize.fn("DATEADD", sequelize.literal("day"), 2, sequelize.col(sequelize.fn('NOW')))
            }).then((tkn) => {
                console.log(tkn);
                res.status(200).json(tkn.toJSON());
            }).catch((e) => {
                res.status(500).json({"message": "Server Error"});
            });
            res.status(200).json({message : "ok", token : token});
        }else{
            res.status(403).send('wrong password')
        }
    }
    }).catch((e) => {
        console.log(e);
        res.status(500).send('unhandled Server error');
    });
}

The Error message :

(node:15798) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client.

I tried creating my Token outside the find block but I'm getting my token variable is undefined. how can i go about storing my token after having created it .

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

0

I understood hat was going on, i had my outer promise going about it's thing and sending me the response

res.status(200).json({message : "ok", token : token});

while the promise of Toen.create was stuck on the way i chose to add two days to the current date with sequelize. After commenting the response I got to handle the error in the Token.create block

I don't think this is the best way to do it so feel free to throw your two cents.

about 4 years ago · Juan Pablo Isaza Relatório

0

That's because code is sending response two times. first time it send response

 res.status(200).json(tkn.toJSON());

and after it code become stuck whenever it get another response.

res.status(200).json({message : "ok", token : token});
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