Node.js Error: Can't set headers after they are sent
The res
object in Express is a subclass of Node.js's http.ServerResponse
(read the http.js source). You are allowed to call res.setHeader(name, value)
as often as you want until you call res.writeHead(statusCode)
. After writeHead
, the headers are baked in and you can only call res.write(data)
res.end(data)
.
The error "Error: Can't set headers after they are sent." means that you're already in the Body or Finished state, but some function tried to set a header or statusCode. When you see this error, try to look for anything that tries to send a header after some of the body has already been written. For example, look for callbacks that are accidentally called twice, or any error that happens after the body is sent.
In your case, you called res.redirect()
, which caused the response to become Finished. Then your code threw an error (res.req
is null). and since the error happened within your actual function(req,res,next)
(not within a callback), Connect was able to catch it and then tried to send a 500 error page. But since the headers were already sent, Node.js's setHeader threw the error that you saw.
Comprehensive list of Node.js/Express response methods and when they must be called:
Response must be in Head and remains in Head:
-
res.writeContinue()
-
res.statusCode = 404
-
res.setHeader(name, value)
-
res.getHeader(name)
-
res.removeHeader(name)
-
res.header(key[, val])
(Express only) -
res.charset = 'utf-8'
(Express only; only affects Express-specific methods) -
res.contentType(type)
(Express only)
Response must be in Head and becomes Body:
Response can be in either Head/Body and remains in Body:
Response can be in either Head/Body and becomes Finished:
Response can be in either Head/Body and remains in its current state:
Response must be in Head and becomes Finished:
-
return next([err])
(Connect/Express only) - Any exceptions within middleware
function(req, res, next)
(Connect/Express only) -
res.send(body|status[, headers|status[, status]])
(Express only) -
res.attachment(filename)
(Express only) -
res.sendfile(path[, options[, callback]])
(Express only) -
res.json(obj[, headers|status[, status]])
(Express only) -
res.redirect(url[, status])
(Express only) -
res.cookie(name, val[, options])
(Express only) -
res.clearCookie(name[, options])
(Express only) -
res.render(view[, options[, fn]])
(Express only) -
res.partial(view[, options])
(Express only)
http://stackoverflow.com/questions/7042340/node-js-error-cant-set-headers-after-they-are-sent