# 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), 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:

1. res.writeContinue()
2. res.statusCode = 404
3. res.setHeader(name, value)
4. res.getHeader(name)
5. res.removeHeader(name)
6. res.header(key[, val]) (Express only)
7. res.charset = 'utf-8' (Express only; only affects Express-specific methods)
8. res.contentType(type) (Express only)

Response must be in Head and becomes Body:

1. res.writeHead(statusCode, [reasonPhrase], [headers])

Response can be in either Head/Body and remains in Body:

1. res.write(chunk, encoding='utf8')

Response can be in either Head/Body and becomes Finished:

1. res.end([data], [encoding])

Response can be in either Head/Body and remains in its current state:

1. res.addTrailers(headers)

Response must be in Head and becomes Finished:

1. return next([err]) (Connect/Express only)
2. Any exceptions within middleware function(req, res, next) (Connect/Express only)
3. res.send(body|status[, headers|status[, status]]) (Express only)
4. res.attachment(filename) (Express only)
5. res.sendfile(path[, options[, callback]]) (Express only)
6. res.json(obj[, headers|status[, status]]) (Express only)
7. res.redirect(url[, status]) (Express only)
8. res.cookie(name, val[, options]) (Express only)
9. res.clearCookie(name[, options]) (Express only)
10. res.render(view[, options[, fn]]) (Express only)
11. res.partial(view[, options]) (Express only)

04-22 9085

09-11 418

06-19 1164

05-12 143

05-02 253

04-30 182

04-30 415

04-29 149

04-29 195

04-28 695

04-28 243

04-27 166

04-25 164

04-24 226

04-23 132

04-22 157

04-21 947

04-18 894

01-15 337

03-27 526

#### 怎样对抗AI骚扰电话

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。