'Node js POST Request error Errorcode: 'ERR_HTTP_HEADERS_SENT' when I send my request with postman [duplicate]

I don't understand why request to create an object is no longer valid. I create models with mysql and sequelize.

I fill in the user's token for each request, to connect, retrieve his profile, retrieve all the articles from the database and it works, but now I can't create any more articles.

I did console.log(req.body)of my function but I have this : {}. My function gives me a 400 error from my first condition.When I send my request, on VSC I have " code: 'ERR_HTTP_HEADERS_SENT'".

I checked the number of characters that should match the sequelize patterns, it's good. I filled in the 3 fields on postman, title, description and userId.

//*******Creating an article*******//
exports.createArticle = (req, res, next) => {
  //Nous allons renvoyer 2 paramêtre //
  const title = req.body.title;
  const description = req.body.description;

  console.log(req.body);
  // Fields must not be empty before sending //
  if (title == null || description == null) {
    res.status(400).json({ message: "content can not empty" });
  }
  console.log(req.body);
  //***Build the request body****/
  const article = Article.build({
    title: req.body.title,
    description: req.body.description,
    userId: req.userId,
  });
  console.log(article);

  //***Save new article***//
  article
    .save()
    .then(() => res.status(201).json({ article }))
    .catch((error) => res.status(400).json({ error }));
};


Solution 1:[1]

As even after returning { message: "content can not empty" }, your code is continuing execution and sends another response, if you didn't provide title or description. Please modify your code as per below code

exports.createArticle = (req, res, next) => {
  //Nous allons renvoyer 2 paramĂȘtre //
  const title = req.body.title;
  const description = req.body.description;

  console.log(req.body);
  // Fields must not be empty before sending //
  if (title == null || description == null) {
    res.status(400).json({ message: "content can not empty" });
    return;
  }
  console.log(req.body);
  //***Build the request body****/
  const article = Article.build({
    title: req.body.title,
    description: req.body.description,
    userId: req.userId,
  });
  console.log(article);

  //***Save new article***//
  article
    .save()
    .then(() => res.status(201).json({ article }))
    .catch((error) => res.status(400).json({ error }));
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ankit Ranjan Sinha