. Advertisement .
..3..
. Advertisement .
..4..
I get the “error [err_http_headers_sent]: cannot set headers after they are sent to the client” issue when I am trying to use Express to make Some APIs in NodeJs:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:371:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
Here is my program:
app.post("/login", (req, res) => {
if (!req.body.username) {
res.status(400).json({
status_code: 0,
error_msg: "Require Params Missing",
});
}
res.status(200).json({
status_code: 1,
data: req.body,
});
});
What’s causing it, and how can it be resolved in the ”error [err_http_headers_sent]: cannot set headers after they are sent to the client”?
The cause: I think this error happens because your function won’t stop while res.status(400).json is running.
The execution of a function is halted when a return statement is used in the function body. A given value is returned to the function caller if specified.
Solution: You can fix this error by using return statement.
In your request handler function, add a return statement as the following:
👇️ Read more: Tips On Fixing The Error “Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client”