skip to Main Content

When I’m sending a POST request to MySql database, it adds the product but it shoots me with that error.

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:387:5)
at ServerResponse.setHeader (node:_http_outgoing:603:11)
at ServerResponse.header (C:UsersDELLDesktopSmall projectnode_modulesexpresslibresponse.js:794:10)
at ServerResponse.send (C:UsersDELLDesktopSmall projectnode_modulesexpresslibresponse.js:174:12)
at Query. (C:UsersDELLDesktopSmall projectserver.js:47:16)
at Query. (C:UsersDELLDesktopSmall projectnode_modulesmysqllibConnection.js:526:10)
at Query._callback (C:UsersDELLDesktopSmall projectnode_modulesmysqllibConnection.js:488:16)
at Query.Sequence.end (C:UsersDELLDesktopSmall projectnode_modulesmysqllibprotocolsequencesSequence.js:83:24)
at Query._handleFinalResultPacket (C:UsersDELLDesktopSmall projectnode_modulesmysqllibprotocolsequencesQuery.js:149:8)
at Query.OkPacket (C:UsersDELLDesktopSmall projectnode_modulesmysqllibprotocolsequencesQuery.js:74:10) {
code: ‘ERR_HTTP_HEADERS_SENT’

app.post("/product", (req, res, next) => {
  let product = {
    product_title: "lool",
    product_price: 4444.12,
    product_type: "sneakers",
    product_brand: "lol",
  };
  let sql = `INSERT INTO products SET ?`;

  db.query(sql, product, (err, result) => {
    if (err) {
      throw err;
    }
    console.log(result);
    return res.send("Completed");
  });

  res.send("Added");
});

2

Answers


  1. You can only use res.send() once, when you use it a second time it throws this error. Just remove this res.send("Added").

    Login or Signup to reply.
  2. If you’re writing asynchronous code, you must keep in mind the timing involved, and you must schedule your responses accordingly:

    app.post("/product", (req, res, next) => {
      // ...
      db.query(sql, product, (err, result) => {
        // ...
    
        // Runs at some point in the distant future in terms of compute time
        return res.send("Completed");
      });
    
      // Runs *immediately*
      res.send("Added");
    });
    

    You cannot have that immediate res.send(), you must remove that. If you want to handle the error, that error handling happens inside the callback.1

    1 This is why using async functions with await makes your code a lot easier to manage.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search