O generates error Can not set headers after they are sent, is running 2 times

0

When the validator returns an error to API to, when I do not have a return to an api error it works normal.

function alterar(req,res){

    validator.validaValores(req.body,(err,data) => {
        if(err){
            console.log(err)
            return res.status(500).json(err)
        }else{
            console.log("Teste")
            repository.alterar(req.body, (err,data) => {
                if(err){
                    return res.status(500).json(err)
                }else{
                    res.status(200).json({mesage: 'Alterado com sucesso!'})
                }    
            })
        }      
    })
}

This is the error, the two validator I give in the code appear there, but should only appear the one with the error message.

{error: 'Invalid data!' }

Testing     _http_outgoing.js: 489         throw new Error ('Can \' t set headers after they are sent. ');         ^

Error: Can't set headers after they are sent.
    at validateHeader (_http_outgoing.js:489:11)
    at ServerResponse.setHeader (_http_outgoing.js:496:3)
    at ServerResponse.header (/home/thiago/projeto/projeto/projeto_api/node_modules/express/lib/response.js:767:10)
    at ServerResponse.send (/home/thiago/projeto/projeto/projeto_api/node_modules/express/lib/response.js:170:12)
    at ServerResponse.json (/home/thiago/projeto/projeto/projeto_api/node_modules/express/lib/response.js:267:15)
    at repository.alterar (/home/thiago/projeto/projeto/projeto_api/src/core/valores/teste/testeController.js:39:37)
    at sql.request.input.input.input.input.input.execute (/home/thiago/projeto/projeto/projeto_api/src/core/valores/teste/testeRepository.js:48:17)
    at /home/thiago/projeto/projeto/projeto_api/node_modules/mssql/lib/main.js:1632:20
    at Request.userCallback (/home/thiago/projeto/projeto/projeto_api/node_modules/mssql/lib/tedious.js:1137:61)
    at Request.callback (/home/thiago/projeto/projeto/projeto_api/node_modules/tedious/lib/request.js:39:27)
[nodemon] app crashed - waiting for file changes before starting...
    
asked by anonymous 04.12.2017 / 13:29

1 answer

0

The problem was that I was twice running the function of my validator so I solved it as follows:

function alterar(req,res){
try{
    validator.validaValores(req.body,(err) => {
        if(err){
            throw err
        }else{
            repository.alterar(req.body, (err,data) => {
                if(err){
                    throw err
                }else{
                    res.status(200).json({mesage:'Alterado com sucesso!'})    
                }    
            })
        }      
    })
}catch(err){
    return res.status(500).json(err)
}

}

I changed the return by throw using try catch to capture the error and thus finalize the function alterar leaving only two returns.

    
04.12.2017 / 15:54