Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Tried async await and return statements but still getting Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

I am using express.js and postgress. I have looked through stack and google and figured out I am getting this error because I am sending more than once. The next rows are added to postgress. I can’t figure out how only send it once. Here is my code.

const newAdmin = async (req, res) => {
  const { admin_name, admin_password, first_name, last_name } = req.body;
  if (!admin_name || !admin_password || !first_name || !last_name) {
    res.status(400).send("You missed a required field");
  }
  const re =
    /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
  if (!re.exec(admin_name)) {
    res.status(400).send("Email is not in proper form");
  }
  if (res.headersSent !== true) {
    res.send("Hello");
  }
  // const insert = ;

  try {
    const admin = await pool.query(
      "insert into admin(admin_name, admin_password, first_name, last_name) values('sst@vcfdvxt.com', 'ffdsadfs', 'fdafd', 'ffaddfs')",
      (error, results) => {
        console.log("hello");
        if (error) {
          throw error;
        } else {
          return res.status(200).json("Insert into table");
        }
      }
    );
    if (!admin) {
      return res.status(400).json("Insert infffdsto table");
    }
  } catch (e) {
    return res.status(400).json("Insert infffdsto table");
    console.log(e);
  }

  res.send("This works");
};

And this is the error I am getting

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

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:399:5)
    at ServerResponse.setHeader (node:_http_outgoing:663:11)
    at ServerResponse.header (/Users/aaronkatz/Documents/course_work/backend/express_node_db/node_modules/express/lib/response.js:794:10)
    at ServerResponse.send (/Users/aaronkatz/Documents/course_work/backend/express_node_db/node_modules/express/lib/response.js:174:12)
    at ServerResponse.json (/Users/aaronkatz/Documents/course_work/backend/express_node_db/node_modules/express/lib/response.js:278:15)
    at newAdmin (/Users/aaronkatz/Documents/course_work/backend/express_node_db/src/controllers/adminController.js:60:28)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}

Node.js v18.14.0
[nodemon] app crashed - waiting for file changes before starting...

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Add a return statement after each of your first three res.send() calls. When you allow execution to continue into the rest of your code, that will let other code try to send a second response to the same request which is what results in the warning you see.

While you may logically think that res.send() ends the processing of the request, it does not stop the Javascript interpreter from still continuing execution of your function. You need a return statement to do that.

Also, do not use both await and a callback on pool.query(). If you’re using a promise-enabled version of your database API, then use only one or the other, not both. If you’re not using a promise-enabled version of your database API, then the await is useless (does nothing).

And, remove the res.send("This works"); because you’ve already sent a response in all the other code paths so you don’t want to be sending a duplicate response.

And lastly, some of your responses are sending JSON and some are sending plain text. That makes this route difficult to use because the client has to branch their code based on the content-type of the response. It is much better (whenever possible), to always send a consistent content-type in the response. In this case, you could just always send JSON and then the client can just know that they’re getting JSON and process the response by parsing the JSON.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading