-
-
Notifications
You must be signed in to change notification settings - Fork 35.5k
Expand file tree
/
Copy pathhttp.md
More file actions
1263 lines (917 loc) Β· 40.6 KB
/
http.md
File metadata and controls
1263 lines (917 loc) Β· 40.6 KB
Edit and raw actions
OlderNewer
Β
1
# HTTP
2
3
Stability: 2 - Stable
4
5
To use the HTTP server and client one must `require('http')`.
6
7
The HTTP interfaces in Node.js are designed to support many features
8
of the protocol which have been traditionally difficult to use.
9
In particular, large, possibly chunk-encoded, messages. The interface is
10
careful to never buffer entire requests or responses--the
11
user is able to stream data.
12
13
HTTP message headers are represented by an object like this:
14
15
```
16
{ 'content-length': '123',
17
'content-type': 'text/plain',
18
'connection': 'keep-alive',
19
'host': 'mysite.com',
20
'accept': '*/*' }
21
```
22
23
Keys are lowercased. Values are not modified.
24
25
In order to support the full spectrum of possible HTTP applications, Node.js's
26
HTTP API is very low-level. It deals with stream handling and message
27
parsing only. It parses a message into headers and body but it does not
28
parse the actual headers or the body.
29
30
See [`message.headers`][] for details on how duplicate headers are handled.
31
32
The raw headers as they were received are retained in the `rawHeaders`
33
property, which is an array of `[key, value, key2, value2, ...]`. For
34
example, the previous message header object might have a `rawHeaders`
35
list like the following:
36
37
```
38
[ 'ConTent-Length', '123456',
39
'content-LENGTH', '123',
40
'content-type', 'text/plain',
41
'CONNECTION', 'keep-alive',
42
'Host', 'mysite.com',
43
'accepT', '*/*' ]
44
```
45
46
## Class: http.Agent
47
48
The HTTP Agent is used for pooling sockets used in HTTP client
49
requests.
50
51
The HTTP Agent also defaults client requests to using
52
Connection:keep-alive. If no pending HTTP requests are waiting on a
53
socket to become free the socket is closed. This means that Node.js's
54
pool has the benefit of keep-alive when under load but still does not
55
require developers to manually close the HTTP clients using
56
KeepAlive.
57
58
If you opt into using HTTP KeepAlive, you can create an Agent object
59
with that flag set to `true`. (See the [constructor options][].)
60
Then, the Agent will keep unused sockets in a pool for later use. They
61
will be explicitly marked so as to not keep the Node.js process running.
62
However, it is still a good idea to explicitly [`destroy()`][] KeepAlive
63
agents when they are no longer in use, so that the Sockets will be shut
64
down.
65
66
Sockets are removed from the agent's pool when the socket emits either
67
a `'close'` event or a special `'agentRemove'` event. This means that if
68
you intend to keep one HTTP request open for a long time and don't
69
want it to stay in the pool you can do something along the lines of:
70
71
```js
72
http.get(options, (res) => {
73
// Do stuff
74
}).on('socket', (socket) => {
75
socket.emit('agentRemove');
76
});
77
```
78
79
Alternatively, you could just opt out of pooling entirely using
80
`agent:false`:
81
82
```js
83
http.get({
84
hostname: 'localhost',
85
port: 80,
86
path: '/',
87
agent: false // create a new agent just for this one request
88
}, (res) => {
89
// Do stuff with response
90
})
91
```
92
93
### new Agent([options])
94
95
* `options` {Object} Set of configurable options to set on the agent.
96
Can have the following fields:
97
* `keepAlive` {Boolean} Keep sockets around in a pool to be used by
98
other requests in the future. Default = `false`
99
* `keepAliveMsecs` {Integer} When using HTTP KeepAlive, how often
100
to send TCP KeepAlive packets over sockets being kept alive.
101
Default = `1000`. Only relevant if `keepAlive` is set to `true`.
102
* `maxSockets` {Number} Maximum number of sockets to allow per
103
host. Default = `Infinity`.
104
* `maxFreeSockets` {Number} Maximum number of sockets to leave open
105
in a free state. Only relevant if `keepAlive` is set to `true`.
106
Default = `256`.
107
108
The default [`http.globalAgent`][] that is used by [`http.request()`][] has all
109
of these values set to their respective defaults.
110
111
To configure any of them, you must create your own [`http.Agent`][] object.
112
113
```js
114
const http = require('http');
115
var keepAliveAgent = new http.Agent({ keepAlive: true });
116
options.agent = keepAliveAgent;
117
http.request(options, onResponseCallback);
118
```
119
120
### agent.createConnection(options[, callback])
121
122
Produces a socket/stream to be used for HTTP requests.
123
124
By default, this function is the same as [`net.createConnection()`][]. However,
125
custom Agents may override this method in case greater flexibility is desired.
126
127
A socket/stream can be supplied in one of two ways: by returning the
128
socket/stream from this function, or by passing the socket/stream to `callback`.
129
130
`callback` has a signature of `(err, stream)`.
131
132
### agent.destroy()
133
134
Destroy any sockets that are currently in use by the agent.
135
136
It is usually not necessary to do this. However, if you are using an
137
agent with KeepAlive enabled, then it is best to explicitly shut down
138
the agent when you know that it will no longer be used. Otherwise,
139
sockets may hang open for quite a long time before the server
140
terminates them.
141
142
### agent.freeSockets
143
144
An object which contains arrays of sockets currently awaiting use by
145
the Agent when HTTP KeepAlive is used. Do not modify.
146
147
### agent.getName(options)
148
149
Get a unique name for a set of request options, to determine whether a
150
connection can be reused. In the http agent, this returns
151
`host:port:localAddress`. In the https agent, the name includes the
152
CA, cert, ciphers, and other HTTPS/TLS-specific options that determine
153
socket reusability.
154
155
Options:
156
157
- `host`: A domain name or IP address of the server to issue the request to.
158
- `port`: Port of remote server.
159
- `localAddress`: Local interface to bind for network connections when issuing
160
the request.
161
162
### agent.maxFreeSockets
163
164
By default set to 256. For Agents supporting HTTP KeepAlive, this
165
sets the maximum number of sockets that will be left open in the free
166
state.
167
168
### agent.maxSockets
169
170
By default set to Infinity. Determines how many concurrent sockets the agent
171
can have open per origin. Origin is either a 'host:port' or
172
'host:port:localAddress' combination.
173
174
### agent.requests
175
176
An object which contains queues of requests that have not yet been assigned to
177
sockets. Do not modify.
178
179
### agent.sockets
180
181
An object which contains arrays of sockets currently in use by the
182
Agent. Do not modify.
183
184
## Class: http.ClientRequest
185
186
This object is created internally and returned from [`http.request()`][]. It
187
represents an _in-progress_ request whose header has already been queued. The
188
header is still mutable using the `setHeader(name, value)`, `getHeader(name)`,
189
`removeHeader(name)` API. The actual header will be sent along with the first
190
data chunk or when closing the connection.
191
192
To get the response, add a listener for `'response'` to the request object.
193
`'response'` will be emitted from the request object when the response
194
headers have been received. The `'response'` event is executed with one
195
argument which is an instance of [`http.IncomingMessage`][].
196
197
During the `'response'` event, one can add listeners to the
198
response object; particularly to listen for the `'data'` event.
199
200
If no `'response'` handler is added, then the response will be
201
entirely discarded. However, if you add a `'response'` event handler,
202
then you **must** consume the data from the response object, either by
203
calling `response.read()` whenever there is a `'readable'` event, or
204
by adding a `'data'` handler, or by calling the `.resume()` method.
205
Until the data is consumed, the `'end'` event will not fire. Also, until
206
the data is read it will consume memory that can eventually lead to a
207
'process out of memory' error.
208
209
Note: Node.js does not check whether Content-Length and the length of the body
210
which has been transmitted are equal or not.
211
212
The request implements the [Writable Stream][] interface. This is an
213
[`EventEmitter`][] with the following events:
214
215
### Event: 'abort'
216
217
`function () { }`
218
219
Emitted when the request has been aborted by the client. This event is only
220
emitted on the first call to `abort()`.
221
222
### Event: 'checkExpectation'
223
224
`function (request, response) { }`
225
226
Emitted each time a request with an http Expect header is received, where the
227
value is not 100-continue. If this event isn't listened for, the server will
228
automatically respond with a 417 Expectation Failed as appropriate.
229
230
Note that when this event is emitted and handled, the `request` event will
231
not be emitted.
232
233
### Event: 'connect'
234
235
`function (response, socket, head) { }`
236
237
Emitted each time a server responds to a request with a `CONNECT` method. If this
238
event isn't being listened for, clients receiving a `CONNECT` method will have
239
their connections closed.
240
241
A client server pair that show you how to listen for the `'connect'` event.
242
243
```js
244
const http = require('http');
245
const net = require('net');
246
const url = require('url');
247
248
// Create an HTTP tunneling proxy
249
var proxy = http.createServer( (req, res) => {
250
res.writeHead(200, {'Content-Type': 'text/plain'});
251
res.end('okay');
252
});
253
proxy.on('connect', (req, cltSocket, head) => {
254
// connect to an origin server
255
var srvUrl = url.parse(`http://${req.url}`);
256
var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, () => {
257
cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
258
'Proxy-agent: Node.js-Proxy\r\n' +
259
'\r\n');
260
srvSocket.write(head);
261
srvSocket.pipe(cltSocket);
262
cltSocket.pipe(srvSocket);
263
});
264
});
265
266
// now that proxy is running
267
proxy.listen(1337, '127.0.0.1', () => {
268
269
// make a request to a tunneling proxy
270
var options = {
271
port: 1337,
272
hostname: '127.0.0.1',
273
method: 'CONNECT',
274
path: 'www.google.com:80'
275
};
276
277
var req = http.request(options);
278
req.end();
279
280
req.on('connect', (res, socket, head) => {
281
console.log('got connected!');
282
283
// make a request over an HTTP tunnel
284
socket.write('GET / HTTP/1.1\r\n' +
285
'Host: www.google.com:80\r\n' +
286
'Connection: close\r\n' +
287
'\r\n');
288
socket.on('data', (chunk) => {
289
console.log(chunk.toString());
290
});
291
socket.on('end', () => {
292
proxy.close();
293
});
294
});
295
});
296
```
297
298
### Event: 'continue'
299
300
`function () { }`
301
302
Emitted when the server sends a '100 Continue' HTTP response, usually because
303
the request contained 'Expect: 100-continue'. This is an instruction that
304
the client should send the request body.
305
306
### Event: 'response'
307
308
`function (response) { }`
309
310
Emitted when a response is received to this request. This event is emitted only
311
once. The `response` argument will be an instance of [`http.IncomingMessage`][].
312
313
### Event: 'socket'
314
315
`function (socket) { }`
316
317
Emitted after a socket is assigned to this request.
318
319
### Event: 'upgrade'
320
321
`function (response, socket, head) { }`
322
323
Emitted each time a server responds to a request with an upgrade. If this
324
event isn't being listened for, clients receiving an upgrade header will have
325
their connections closed.
326
327
A client server pair that show you how to listen for the `'upgrade'` event.
328
329
```js
330
const http = require('http');
331
332
// Create an HTTP server
333
var srv = http.createServer( (req, res) => {
334
res.writeHead(200, {'Content-Type': 'text/plain'});
335
res.end('okay');
336
});
337
srv.on('upgrade', (req, socket, head) => {
338
socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
339
'Upgrade: WebSocket\r\n' +
340
'Connection: Upgrade\r\n' +
341
'\r\n');
342
343
socket.pipe(socket); // echo back
344
});
345
346
// now that server is running
347
srv.listen(1337, '127.0.0.1', () => {
348
349
// make a request
350
var options = {
351
port: 1337,
352
hostname: '127.0.0.1',
353
headers: {
354
'Connection': 'Upgrade',
355
'Upgrade': 'websocket'
356
}
357
};
358
359
var req = http.request(options);
360
req.end();
361
362
req.on('upgrade', (res, socket, upgradeHead) => {
363
console.log('got upgraded!');
364
socket.end();
365
process.exit(0);
366
});
367
});
368
```
369
370
### request.abort()
371
372
Marks the request as aborting. Calling this will cause remaining data
373
in the response to be dropped and the socket to be destroyed.
374
375
### request.end([data][, encoding][, callback])
376
377
Finishes sending the request. If any parts of the body are
378
unsent, it will flush them to the stream. If the request is
379
chunked, this will send the terminating `'0\r\n\r\n'`.
380
381
If `data` is specified, it is equivalent to calling
382
[`response.write(data, encoding)`][] followed by `request.end(callback)`.
383
384
If `callback` is specified, it will be called when the request stream
385
is finished.
386
387
### request.flushHeaders()
388
389
Flush the request headers.
390
391
For efficiency reasons, Node.js normally buffers the request headers until you
392
call `request.end()` or write the first chunk of request data. It then tries
393
hard to pack the request headers and data into a single TCP packet.
394
395
That's usually what you want (it saves a TCP round-trip) but not when the first
396
data isn't sent until possibly much later. `request.flushHeaders()` lets you bypass
397
the optimization and kickstart the request.
398
399
### request.setNoDelay([noDelay])
400
401
Once a socket is assigned to this request and is connected
402
[`socket.setNoDelay()`][] will be called.
403
404
### request.setSocketKeepAlive([enable][, initialDelay])
405
406
Once a socket is assigned to this request and is connected
407
[`socket.setKeepAlive()`][] will be called.
408
409
### request.setTimeout(timeout[, callback])
410
411
Once a socket is assigned to this request and is connected
412
[`socket.setTimeout()`][] will be called.
413
414
* `timeout` {Number} Milliseconds before a request is considered to be timed out.
415
* `callback` {Function} Optional function to be called when a timeout occurs. Same as binding to the `timeout` event.
416
417
### request.write(chunk[, encoding][, callback])
418
419
Sends a chunk of the body. By calling this method
420
many times, the user can stream a request body to a
421
server--in that case it is suggested to use the
422
`['Transfer-Encoding', 'chunked']` header line when
423
creating the request.
424
425
The `chunk` argument should be a [`Buffer`][] or a string.
426
427
The `encoding` argument is optional and only applies when `chunk` is a string.
428
Defaults to `'utf8'`.
429
430
The `callback` argument is optional and will be called when this chunk of data
431
is flushed.
432
433
Returns `request`.
434
435
## Class: http.Server
436
437
ThisΒ class inherits from [`net.Server`][] and has the following additional events:
438
439
### Event: 'checkContinue'
440
441
`function (request, response) { }`
442
443
Emitted each time a request with an http Expect: 100-continue is received.
444
If this event isn't listened for, the server will automatically respond
445
with a 100 Continue as appropriate.
446
447
Handling this event involves calling [`response.writeContinue()`][] if the client
448
should continue to send the request body, or generating an appropriate HTTP
449
response (e.g., 400 Bad Request) if the client should not continue to send the
450
request body.
451
452
Note that when this event is emitted and handled, the `'request'` event will
453
not be emitted.
454
455
### Event: 'clientError'
456
457
`function (exception, socket) { }`
458
459
If a client connection emits an `'error'` event, it will be forwarded here.
460
Listener of this event is responsible for closing/destroying the underlying
461
socket. For example, one may wish to more gracefully close the socket with an
462
HTTP '400 Bad Request' response instead of abruptly severing the connection.
463
464
Default behavior is to destroy the socket immediately on malformed request.
465
466
`socket` is the [`net.Socket`][] object that the error originated from.
467
468
```js
469
const http = require('http');
470
471
const server = http.createServer((req, res) => {
472
res.end();
473
});
474
server.on('clientError', (err, socket) => {
475
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
476
});
477
server.listen(8000);
478
```
479
480
When the `'clientError'` event occurs, there is no `request` or `response`
481
object, so any HTTP response sent, including response headers and payload,
482
*must* be written directly to the `socket` object. Care must be taken to
483
ensure the response is a properly formatted HTTP response message.
484
485
### Event: 'close'
486
487
`function () { }`
488
489
Emitted when the server closes.
490
491
### Event: 'connect'
492
493
`function (request, socket, head) { }`
494
495
Emitted each time a client requests a http `CONNECT` method. If this event isn't
496
listened for, then clients requesting a `CONNECT` method will have their
497
connections closed.
498
499
* `request` is the arguments for the http request, as it is in the request
500
event.
501
* `socket` is the network socket between the server and client.
502
* `head` is an instance of Buffer, the first packet of the tunneling stream,
503
this may be empty.
504
505
After this event is emitted, the request's socket will not have a `'data'`
506
event listener, meaning you will need to bind to it in order to handle data
507
sent to the server on that socket.
508
509
### Event: 'connection'
510
511
`function (socket) { }`
512
513
When a new TCP stream is established. `socket` is an object of type
514
[`net.Socket`][]. Usually users will not want to access this event. In
515
particular, the socket will not emit `'readable'` events because of how
516
the protocol parser attaches to the socket. The `socket` can also be
517
accessed at `request.connection`.
518
519
### Event: 'request'
520
521
`function (request, response) { }`
522
523
Emitted each time there is a request. Note that there may be multiple requests
524
per connection (in the case of keep-alive connections).
525
`request` is an instance of [`http.IncomingMessage`][] and `response` is
526
an instance of [`http.ServerResponse`][].
527
528
### Event: 'upgrade'
529
530
`function (request, socket, head) { }`
531
532
Emitted each time a client requests a http upgrade. If this event isn't
533
listened for, then clients requesting an upgrade will have their connections
534
closed.
535
536
* `request` is the arguments for the http request, as it is in the request
537
event.
538
* `socket` is the network socket between the server and client.
539
* `head` is an instance of Buffer, the first packet of the upgraded stream,
540
this may be empty.
541
542
After this event is emitted, the request's socket will not have a `'data'`
543
event listener, meaning you will need to bind to it in order to handle data
544
sent to the server on that socket.
545
546
### server.close([callback])
547
548
Stops the server from accepting new connections. See [`net.Server.close()`][].
549
550
### server.listen(handle[, callback])
551
552
* `handle` {Object}
553
* `callback` {Function}
554
555
The `handle` object can be set to either a server or socket (anything
556
with an underlying `_handle` member), or a `{fd: <n>}` object.
557
558
This will cause the server to accept connections on the specified
559
handle, but it is presumed that the file descriptor or handle has
560
already been bound to a port or domain socket.
561
562
Listening on a file descriptor is not supported on Windows.
563
564
This function is asynchronous. The last parameter `callback` will be added as
565
a listener for the `'listening'` event. See also [`net.Server.listen()`][].
566
567
Returns `server`.
568
569
### server.listen(path[, callback])
570
571
Start a UNIX socket server listening for connections on the given `path`.
572
573
This function is asynchronous. The last parameter `callback` will be added as
574
a listener for the `'listening'` event. See also [`net.Server.listen(path)`][].
575
576
### server.listen(port[, hostname][, backlog][, callback])
577
578
Begin accepting connections on the specified `port` and `hostname`. If the
579
`hostname` is omitted, the server will accept connections on any IPv6 address
580
(`::`) when IPv6 is available, or any IPv4 address (`0.0.0.0`) otherwise. A
581
port value of zero will assign a random port.
582
583
To listen to a unix socket, supply a filename instead of port and hostname.
584
585
Backlog is the maximum length of the queue of pending connections.
586
The actual length will be determined by your OS through sysctl settings such as
587
`tcp_max_syn_backlog` and `somaxconn` on linux. The default value of this
588
parameter is 511 (not 512).
589
590
This function is asynchronous. The last parameter `callback` will be added as
591
a listener for the `'listening'` event. See also [`net.Server.listen(port)`][].
592
593
### server.listening
594
595
A Boolean indicating whether or not the server is listening for
596
connections.
597
598
### server.maxHeadersCount
599
600
Limits maximum incoming headers count, equal to 1000 by default. If set to 0 -
601
no limit will be applied.
602
603
### server.setTimeout(msecs, callback)
604
605
* `msecs` {Number}
606
* `callback` {Function}
607
608
Sets the timeout value for sockets, and emits a `'timeout'` event on
609
the Server object, passing the socket as an argument, if a timeout
610
occurs.
611
612
If there is a `'timeout'` event listener on the Server object, then it
613
will be called with the timed-out socket as an argument.
614
615
By default, the Server's timeout value is 2 minutes, and sockets are
616
destroyed automatically if they time out. However, if you assign a
617
callback to the Server's `'timeout'` event, then you are responsible
618
for handling socket timeouts.
619
620
Returns `server`.
621
622
### server.timeout
623
624
* {Number} Default = 120000 (2 minutes)
625
626
The number of milliseconds of inactivity before a socket is presumed
627
to have timed out.
628
629
Note that the socket timeout logic is set up on connection, so
630
changing this value only affects *new* connections to the server, not
631
any existing connections.
632
633
Set to 0 to disable any kind of automatic timeout behavior on incoming
634
connections.
635
636
## Class: http.ServerResponse
637
638
This object is created internally by a HTTP server--not by the user. It is
639
passed as the second parameter to the `'request'` event.
640
641
The response implements, but does not inherit from, the [Writable Stream][]
642
interface. This is an [`EventEmitter`][] with the following events:
643
644
### Event: 'close'
645
646
`function () { }`
647
648
Indicates that the underlying connection was terminated before
649
[`response.end()`][] was called or able to flush.
650
651
### Event: 'finish'
652
653
`function () { }`
654
655
Emitted when the response has been sent. More specifically, this event is
656
emitted when the last segment of the response headers and body have been
657
handed off to the operating system for transmission over the network. It
658
does not imply that the client has received anything yet.
659
660
After this event, no more events will be emitted on the response object.
661
662
### response.addTrailers(headers)
663
664
This method adds HTTP trailing headers (a header but at the end of the
665
message) to the response.
666
667
Trailers will **only** be emitted if chunked encoding is used for the
668
response; if it is not (e.g., if the request was HTTP/1.0), they will
669
be silently discarded.
670
671
Note that HTTP requires the `Trailer` header to be sent if you intend to
672
emit trailers, with a list of the header fields in its value. E.g.,
673
674
```js
675
response.writeHead(200, { 'Content-Type': 'text/plain',
676
'Trailer': 'Content-MD5' });
677
response.write(fileData);
678
response.addTrailers({'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667'});
679
response.end();
680
```
681
682
Attempting to set a header field name or value that contains invalid characters
683
will result in a [`TypeError`][] being thrown.
684
685
### response.end([data][, encoding][, callback])
686
687
This method signals to the server that all of the response headers and body
688
have been sent; that server should consider this message complete.
689
The method, `response.end()`, MUST be called on each response.
690
691
If `data` is specified, it is equivalent to calling
692
[`response.write(data, encoding)`][] followed by `response.end(callback)`.
693
694
If `callback` is specified, it will be called when the response stream
695
is finished.
696
697
### response.finished
698
699
Boolean value that indicates whether the response has completed. Starts
700
as `false`. After [`response.end()`][] executes, the value will be `true`.
701
702
### response.getHeader(name)
703
704
Reads out a header that's already been queued but not sent to the client. Note
705
that the name is case insensitive. This can only be called before headers get
706
implicitly flushed.
707
708
Example:
709
710
```js
711
var contentType = response.getHeader('content-type');
712
```
713
714
### response.headersSent
715
716
Boolean (read-only). True if headers were sent, false otherwise.
717
718
### response.removeHeader(name)
719
720
Removes a header that's queued for implicit sending.
721
722
Example:
723
724
```js
725
response.removeHeader('Content-Encoding');
726
```
727
728
### response.sendDate
729
730
When true, the Date header will be automatically generated and sent in
731
the response if it is not already present in the headers. Defaults to true.
732
733
This should only be disabled for testing; HTTP requires the Date header
734
in responses.
735
736
### response.setHeader(name, value)
737
738
Sets a single header value for implicit headers. If this header already exists
739
in the to-be-sent headers, its value will be replaced. Use an array of strings
740
here if you need to send multiple headers with the same name.
741
742
Example:
743
744
```js
745
response.setHeader('Content-Type', 'text/html');
746
```
747
748
or
749
750
```js
751
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
752
```
753
754
Attempting to set a header field name or value that contains invalid characters
755
will result in a [`TypeError`][] being thrown.
756
757
When headers have been set with [`response.setHeader()`][], they will be merged with
758
any headers passed to [`response.writeHead()`][], with the headers passed to
759
[`response.writeHead()`][] given precedence.
760
761
```js
762
// returns content-type = text/plain
763
const server = http.createServer((req,res) => {
764
res.setHeader('Content-Type', 'text/html');
765
res.setHeader('X-Foo', 'bar');
766
res.writeHead(200, {'Content-Type': 'text/plain'});
767
res.end('ok');
768
});
769
```
770
771
### response.setTimeout(msecs, callback)
772
773
* `msecs` {Number}
774
* `callback` {Function}
775
776
Sets the Socket's timeout value to `msecs`. If a callback is
777
provided, then it is added as a listener on the `'timeout'` event on
778
the response object.
779
780
If no `'timeout'` listener is added to the request, the response, or
781
the server, then sockets are destroyed when they time out. If you
782
assign a handler on the request, the response, or the server's
783
`'timeout'` events, then it is your responsibility to handle timed out
784
sockets.
785
786
Returns `response`.
787
788
### response.statusCode
789
790
When using implicit headers (not calling [`response.writeHead()`][] explicitly),
791
this property controls the status code that will be sent to the client when
792
the headers get flushed.
793
794
Example:
795
796
```js
797
response.statusCode = 404;
798
```
799
800
After response header was sent to the client, this property indicates the
801
status code which was sent out.
802
803
### response.statusMessage
804
805
When using implicit headers (not calling [`response.writeHead()`][] explicitly), this property
806
controls the status message that will be sent to the client when the headers get
807
flushed. If this is left as `undefined` then the standard message for the status
808
code will be used.
809
810
Example:
811
812
```js
813
response.statusMessage = 'Not found';
814
```
815
816
After response header was sent to the client, this property indicates the
817
status message which was sent out.
818
819
### response.write(chunk[, encoding][, callback])
820
821
If this method is called and [`response.writeHead()`][] has not been called,
822
it will switch to implicit header mode and flush the implicit headers.
823
824
This sends a chunk of the response body. This method may
825
be called multiple times to provide successive parts of the body.
826
827
`chunk` can be a string or a buffer. If `chunk` is a string,
828
the second parameter specifies how to encode it into a byte stream.
829
By default the `encoding` is `'utf8'`. The last parameter `callback`
830
will be called when this chunk of data is flushed.
831
832
**Note**: This is the raw HTTP body and has nothing to do with
833
higher-level multi-part body encodings that may be used.
834
835
The first time [`response.write()`][] is called, it will send the buffered
836
header information and the first body to the client. The second time
837
[`response.write()`][] is called, Node.js assumes you're going to be streaming
838
data, and sends that separately. That is, the response is buffered up to the
839
first chunk of body.
840
841
Returns `true` if the entire data was flushed successfully to the kernel
842
buffer. Returns `false` if all or part of the data was queued in user memory.
843
`'drain'` will be emitted when the buffer is free again.
844
845
### response.writeContinue()
846
847
Sends a HTTP/1.1 100 Continue message to the client, indicating that
848
the request body should be sent. See the [`'checkContinue'`][] event on `Server`.
849
850
### response.writeHead(statusCode[, statusMessage][, headers])
851
852
Sends a response header to the request. The status code is a 3-digit HTTP
853
status code, like `404`. The last argument, `headers`, are the response headers.
854
Optionally one can give a human-readable `statusMessage` as the second
855
argument.
856
857
Example:
858
859
```js
860
var body = 'hello world';
861
response.writeHead(200, {
862
'Content-Length': body.length,
863
'Content-Type': 'text/plain' });
864
```
865
866
This method must only be called once on a message and it must
867
be called before [`response.end()`][] is called.
868
869
If you call [`response.write()`][] or [`response.end()`][] before calling this,
870
the implicit/mutable headers will be calculated and call this function for you.
871
872
When headers have been set with [`response.setHeader()`][], they will be merged with
873
any headers passed to [`response.writeHead()`][], with the headers passed to
874
[`response.writeHead()`][] given precedence.
875
876
```js
877
// returns content-type = text/plain
878
const server = http.createServer((req,res) => {
879
res.setHeader('Content-Type', 'text/html');
880
res.setHeader('X-Foo', 'bar');
881
res.writeHead(200, {'Content-Type': 'text/plain'});
882
res.end('ok');
883
});
884
```
885
886
Note that Content-Length is given in bytes not characters. The above example
887
works because the string `'hello world'` contains only single byte characters.
888
If the body contains higher coded characters then `Buffer.byteLength()`
889
should be used to determine the number of bytes in a given encoding.
890
And Node.js does not check whether Content-Length and the length of the body
891
which has been transmitted are equal or not.
892
893
Attempting to set a header field name or value that contains invalid characters
894
will result in a [`TypeError`][] being thrown.
895
896
## Class: http.IncomingMessage
897
898
An `IncomingMessage` object is created by [`http.Server`][] or
899
[`http.ClientRequest`][] and passed as the first argument to the `'request'`
900
and `'response'` event respectively. It may be used to access response status,
901
headers and data.
902
903
It implements the [Readable Stream][] interface, as well as the
904
following additional events, methods, and properties.
905
906
### Event: 'close'
907
908
`function () { }`
909
910
Indicates that the underlying connection was closed.
911
Just like `'end'`, this event occurs only once per response.
912
913
### message.headers
914
915
The request/response headers object.
916
917
Key-value pairs of header names and values. Header names are lower-cased.
918
Example:
919
920
```js
921
// Prints something like:
922
//
923
// { 'user-agent': 'curl/7.22.0',
924
// host: '127.0.0.1:8000',
925
// accept: '*/*' }
926
console.log(request.headers);
927
```
928
929
Duplicates in raw headers are handled in the following ways, depending on the
930
header name:
931
932
* Duplicates of `age`, `authorization`, `content-length`, `content-type`,
933
`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,
934
`last-modified`, `location`, `max-forwards`, `proxy-authorization`, `referer`,
935
`retry-after`, or `user-agent` are discarded.
936
* `set-cookie` is always an array. Duplicates are added to the array.
937
* For all other headers, the values are joined together with ', '.
938
939
### message.httpVersion
940
941
In case of server request, the HTTP version sent by the client. In the case of
942
client response, the HTTP version of the connected-to server.
943
Probably either `'1.1'` or `'1.0'`.
944
945
Also `message.httpVersionMajor` is the first integer and
946
`message.httpVersionMinor` is the second.
947
948
### message.method
949
950
**Only valid for request obtained from [`http.Server`][].**
951
952
The request method as a string. Read only. Example:
953
`'GET'`, `'DELETE'`.
954
955
### message.rawHeaders
956
957
The raw request/response headers list exactly as they were received.
958
959
Note that the keys and values are in the same list. It is *not* a
960
list of tuples. So, the even-numbered offsets are key values, and the
961
odd-numbered offsets are the associated values.
962
963
Header names are not lowercased, and duplicates are not merged.
964
965
```js
966
// Prints something like:
967
//
968
// [ 'user-agent',
969
// 'this is invalid because there can be only one',
970
// 'User-Agent',
971
// 'curl/7.22.0',
972
// 'Host',
973
// '127.0.0.1:8000',
974
// 'ACCEPT',
975
// '*/*' ]
976
console.log(request.rawHeaders);
977
```
978
979
### message.rawTrailers
980
981
The raw request/response trailer keys and values exactly as they were
982
received. Only populated at the `'end'` event.
983
984
### message.setTimeout(msecs, callback)
985
986
* `msecs` {Number}
987
* `callback` {Function}
988
989
Calls `message.connection.setTimeout(msecs, callback)`.
990
991
Returns `message`.
992
993
### message.statusCode
994
995
**Only valid for response obtained from [`http.ClientRequest`][].**
996
997
The 3-digit HTTP response status code. E.G. `404`.
998
999
### message.statusMessage
1000