Node.js 使用 postman 测试时出错(错误 [ERR_HTTP_HEADERS_SENT]:发送到客户端后无法设置 headers)

Node.js Error when testing with postman (Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client)

我在尝试通过 Postman 执行 post 请求时收到错误消息“在将它们发送到客户端后无法设置 headers”。我的请求包含以下 body:

{ "name": "新类别1" }

我的代码可能会帮助您理解问题:

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"
        });
    } 
});

});

完整的错误信息:

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...

如果 errors.length 为真,则您将发送第一个响应。

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

db.all(qry, params, (err) => { 中,您正在发送第二个回复。这是不允许的,会导致错误。

您可以在第一次回复后return:

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"
      });
    } 
  });
});