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