Error while executing POST method

Asked

Viewed 320 times

0

I am facing a problem regarding the POST method, when triggering this method it normally inserts in the database, but the application (Node index.js) is finished, at the command prompt I get this error:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

still at the prompt, refers to the line:

At query. _callback (C: Users abc Desktop Backend index.js:67:13)

POST CODE:

router.post('/usuarios', (req, res) =>{
    const nome = req.body.nome.substring(0,255);
    const email = req.body.email.substring(0,255);
    const senha = req.body.senha.substring(0,255);
    execSQLQuery(`INSERT INTO usuario(nome,email,senha) VALUES('${nome}','${email}','${senha}')`, res);
    res.sendStatus(200);
});

COMPLETE CODE:

const express = require('express');
const app = express();         
const bodyParser = require('body-parser');
const port = 3000; //porta padrão
const mysql      = require('mysql');

//configurando o body parser para pegar POSTS mais tarde
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

//definindo as rotas
const router = express.Router();
router.get('/', (req, res) => res.json({ message: 'Funcionando!' }));

router.get('/filmes/:id?', (req, res) =>{
    let filter = '';
    if(req.params.id) filter = ' WHERE ID=' + parseInt(req.params.id);
    execSQLQuery('SELECT * FROM filme' + filter, res);
});

router.get('/usuarios/:id?', (req, res) =>{
    let filter = '';
    if(req.params.id) filter = ' WHERE ID=' + parseInt(req.params.id);
    execSQLQuery('SELECT * FROM usuario' + filter, res);
});

router.delete('/usuarios/:id', (req, res) =>{
    execSQLQuery('DELETE FROM usuario WHERE ID=' + parseInt(req.params.id), res);
    res.sendStatus(200);
});

router.post('/usuarios', (req, res) =>{
    const nome = req.body.nome.substring(0,255);
    const email = req.body.email.substring(0,255);
    const senha = req.body.senha.substring(0,255);
    execSQLQuery(`INSERT INTO usuario(nome,email,senha) VALUES('${nome}','${email}','${senha}')`, res);
    res.sendStatus(200);
});

router.patch('/usuarios/:id', (req, res) =>{
    const id = parseInt(req.params.id);
    const nome = req.body.nome.substring(0,255);
    const email = req.body.email.substring(0,255);
    const senha = req.body.senha.substring(0,255);
    execSQLQuery(`UPDATE usuario SET Nome='${nome}', Email='${email}', Senha='${senha}' WHERE ID=${id}`, res);
    res.sendStatus(200);
});

app.use('/', router);

//inicia o servidor
app.listen(port);
console.log('API funcionando!');

function execSQLQuery(sqlQry, res){
  const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'locadora'
  });

  connection.query(sqlQry, function(error, results, fields){
      if(error) 
        res.json(error);
      else
        res.json(results); //ERRO ACONTECE AQUI
      connection.end();
      console.log('executou!');
  });
}
  • Can you identify the line that happened the problem in the code that Voce provided? You gave the number but it is not possible to know on which code and on which line here.

  • Connection.query(sqlQry, Function(error, Results, Fields){ if(error) res.json(error); Else res.json(Results); Connection.end(); console.log('executed! '); }); LINE -> res.json(Results);

1 answer

1


According to the error message,

Cannot set headers after they are sent to the client

The answer is being modified after it has been sent. Looking at the code, you send the answer in the function execSQLQuery(), then after calling this function, you can no longer modify its res, how are you doing in router.delete, .post, and .patch.

One solution is to pass http status code as an argument to execSQLQuery(), that will use the code when sending the reply using res there.

Another way is to receive a callback as a parameter for execSQLQuery(), which you can pass from where you call the function, providing the code to execute after running the query. Thus, you do not need to pass res as a parameter to execSQLQuery(). Follow the example:

function execSQLQuery(sqlQry, callback){
  const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'locadora'
  });

  connection.query(sqlQry, function(error, results, fields){
      if(error) 
        callback(error);
      else
        callback(null, results);
      connection.end();
      console.log('executou!');
  });
}

Calling for:

execSQLQuery(`INSERT INTO .........`, function(err, result) {
  if (err) {
    res.status(500); // seta o status aqui
    return res.json(err);
  }
  res.status(200); // seta o status aqui (mas 200 deve ser padrao)
  res.json(result);
})
  • It worked by removing the line res.sendStatus(200); from all methods

  • @Henriquehermes updated the answer with example of the use of callback, which is the Pattern used in Nodejs originally.

Browser other questions tagged

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