Error executing POST method

0

I'm facing a problem with the POST method, when I trigger this method it normally inserts into the database, but the application (node index.js) is terminated, at the command prompt I get this error:

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

Still at the prompt, it 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!');
  });
}
    
asked by anonymous 06.12.2017 / 18:51

1 answer

1

According to the error message,

Cannot set headers after they are sent to the client

The response is being modified after it has been submitted. Looking at the code, you send the answer in the execSQLQuery() function, so after calling this function, you can no longer modify its res , as you are doing in router.delete , .post , and .patch . / p>

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

Another way is to get a callback as a parameter to execSQLQuery (), which you can pass from where you call the function, providing the code to execute after running the query. This way, you do not need to pass res as parameter to execSQLQuery (). Here's 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!');
  });
}

Call:

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);
})
    
06.12.2017 / 19:01