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).
the headers are baked in and you can only call res.write(data),
and finally 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: