-1

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:\Users\DELL\Desktop\Small project\node_modules\express\lib\response.js:794:10) at ServerResponse.send (C:\Users\DELL\Desktop\Small project\node_modules\express\lib\response.js:174:12) at Query. (C:\Users\DELL\Desktop\Small project\server.js:47:16) at Query. (C:\Users\DELL\Desktop\Small project\node_modules\mysql\lib\Connection.js:526:10) at Query._callback (C:\Users\DELL\Desktop\Small project\node_modules\mysql\lib\Connection.js:488:16) at Query.Sequence.end (C:\Users\DELL\Desktop\Small project\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24) at Query._handleFinalResultPacket (C:\Users\DELL\Desktop\Small project\node_modules\mysql\lib\protocol\sequences\Query.js:149:8) at Query.OkPacket (C:\Users\DELL\Desktop\Small project\node_modules\mysql\lib\protocol\sequences\Query.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");
});
  • 1
    Does this answer your question? [ERR\_HTTP\_HEADERS\_SENT: Cannot set headers after they are sent to the client](https://stackoverflow.com/questions/52122272/err-http-headers-sent-cannot-set-headers-after-they-are-sent-to-the-client) – esqew Oct 09 '22 at 01:17

2 Answers2

0

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

Lukas
  • 2,263
  • 1
  • 4
  • 15
0

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.

tadman
  • 208,517
  • 23
  • 234
  • 262