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