My Express app has the following endpoint:
app.post('/test', myFunc)
with the following endpoint handler function:
const bcryptjs = require('bcryptjs')
function myFunc(req, res) {
let password = 'password1234'
let saltRounds = 10
bcryptjs.hash(password, saltRounds, function(err, hash) {
res.send({success: true})
})
.catch(function(err) {
res.send({success: false})
})
}
Now, I know that a bcryptjs.hash
function call doesn't allow a .catch
to be chained on the end of it. My question is more about the type of error message that pops up when this endpoint and its handler function are run, which is:
node:_http_outgoing:576
throw new ERR_HTTP_HEADERS_SENT('set');
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
In my experience, I've found that this type of error typically pops up when an endpoint handler function does two res.send
calls in the same function execution, or something like unto it (doing res.send().json()
or res.sendStatus().send()
, etc.). But it doesn't look my code is violating that idea, and just to be doubly sure, I've commented out the .catch
's res.send
(which wasn't being run the first place, anyway), so that there is only one res.send
in the whole function:
const bcryptjs = require('bcryptjs')
function myFunc(req, res) {
let password = 'password1234'
let saltRounds = 10
bcryptjs.hash(password, saltRounds, function(err, hash) {
res.send({success: true})
})
.catch(function(err) {
//res.send({success: false})
})
}
But the error still shows up. Just to ensure that it is the mere presence of the .catch
that makes the error appear, I change my endpoint handler function to
const bcryptjs = require('bcryptjs')
function myFunc(req, res) {
let password = 'password1234'
let saltRounds = 10
bcryptjs.hash(password, saltRounds, function(err, hash) {
res.send({success: true})
})
}
and no errors are thrown.
My question isn't so much about why an error is thrown when there is a .catch
, but more: why this particular error? Are headers actually trying to be set after a response to the client was sent? And if so, what code is setting those headers?