Home > OS >  Node.js Error when testing with postman (Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after the
Node.js Error when testing with postman (Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after the

Time:04-07

I'm getting the error "Cannot set headers after they are sent to the client", when trying to do a post request via Postman. My request contains the following body:

{ "name": "New category 1" }

My code might help you to understand the question:

function categoryValidator(category) {
return /^[a-zA-Z\s]*$/.test(category);} 

router.post('/', function (req, res) {

let errors = [];

if (!categoryValidator(req.body.name)) {
    errors.push("Naam mag alleen letters en spaties bevatten");
}
if (req.body.name.length < 2) {
    errors.push("Naam moet een minimale lengte van 2 karakters hebbben");
}
console.log(errors.length);

if (errors.length) {
    res.status(400).json({ errors });
}

let qry = `INSERT INTO "Categories" (name) VALUES(?)`;

let params = [req.body.name];
db.all(qry, params, (err) => {
    if (err) {
        res.status(400).json({ error: err.message });
        return;
    } else { 
        res.status(200);
        res.json({
            "message": "succes"
        });
    } 
});

});

The complete error message:

node:internal/errors:464
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:371:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    at ServerResponse.header (C:\Users\DaveP\Documents\Projecten\beddenshopv2\api\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (C:\Users\DaveP\Documents\Projecten\beddenshopv2\api\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (C:\Users\DaveP\Documents\Projecten\beddenshopv2\api\node_modules\express\lib\response.js:267:15)
    at Statement.<anonymous> (C:\Users\DaveP\Documents\Projecten\beddenshopv2\api\routes\categories.js:62:17)
    at Statement.replacement (C:\Users\DaveP\Documents\Projecten\beddenshopv2\api\node_modules\sqlite3\lib\trace.js:25:27) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...

CodePudding user response:

If errors.length is truthy, you're sending the first response.

if (errors.length) {
  res.status(400).json({ errors });
  return;
}

In db.all(qry, params, (err) => { you're sending the second response. That's not allowed and causes the error.

You can return after the first response:

function categoryValidator(category) {
  return /^[a-zA-Z\s]*$/.test(category);
}

router.post('/', function (req, res) {

  let errors = [];

  if (!categoryValidator(req.body.name)) {
    errors.push("Naam mag alleen letters en spaties bevatten");
  }
  if (req.body.name.length < 2) {
    errors.push("Naam moet een minimale lengte van 2 karakters hebbben");
  }
  console.log(errors.length);

  if (errors.length) {
    res.status(400).json({ errors });
    return;
  }

  let qry = `INSERT INTO "Categories" (name) VALUES(?)`;

  let params = [req.body.name];
  db.all(qry, params, (err) => {
    if (err) {
      res.status(400).json({ error: err.message });
        return;
    } else { 
      res.status(200);
      res.json({
        "message": "succes"
      });
    } 
  });
});
  • Related