'clientError' 事件


如果客户端连接触发 'error' 事件,则会在此处转发。 此事件的监听器负责关闭或销毁底层套接字。 例如,用户可能希望使用自定义 HTTP 响应更优雅地关闭套接字,而不是突然切断连接。

默认行为是尽可能使用 HTTP 400 Bad Request 响应关闭套接字,否则立即销毁套接字。

socket 是发生错误的 net.Socket 对象。

const http = require('http');

const server = http.createServer((req, res) => {
  res.end();
});
server.on('clientError', (err, socket) => {
  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
server.listen(8000);

'clientError' 事件发生时,没有 requestresponse 对象,因此必须将发送的任何 HTTP 响应(包括响应头和有效负载)直接写入 socket 对象。 必须注意确保响应是格式正确的 HTTP 响应消息。

errError 实例,有以下两个额外的部分:

  • bytesParsed: Node.js 可能正确解析的请求包的字节数。
  • rawPacket: 当前请求的原始数据包。

If a client connection emits an 'error' event, it will be forwarded here. Listener of this event is responsible for closing/destroying the underlying socket. For example, one may wish to more gracefully close the socket with a custom HTTP response instead of abruptly severing the connection.

Default behavior is to close the socket with an HTTP '400 Bad Request' response if possible, otherwise the socket is immediately destroyed.

socket is the net.Socket object that the error originated from.

const http = require('http');

const server = http.createServer((req, res) => {
  res.end();
});
server.on('clientError', (err, socket) => {
  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
server.listen(8000);

When the 'clientError' event occurs, there is no request or response object, so any HTTP response sent, including response headers and payload, must be written directly to the socket object. Care must be taken to ensure the response is a properly formatted HTTP response message.

err is an instance of Error with two extra columns:

  • bytesParsed: the bytes count of request packet that Node.js may have parsed correctly;
  • rawPacket: the raw packet of current request.