node:http module provides HTTP server and client functionality.
Import
Class: http.Server
This class is used to create an HTTP server.Creating a Server
Events
Event: ‘request’
requestresponse
Event: ‘connection’
socket
Event: ‘close’
Emitted when the server closes.Event: ‘clientError’
exceptionsocket
Methods
server.listen([port][, host][, callback])
porthostcallback
server.close([callback])
callback
server.setTimeout([msecs][, callback])
msecsDefault:120000(2 minutes)callback
Properties
server.timeout
- Type: Default: 0 (no timeout)
server.keepAliveTimeout
- Type: Default:
5000(5 seconds)
server.maxHeadersCount
- Type: Default:
2000
Class: http.IncomingMessage
AnIncomingMessage object is created by http.Server or http.ClientRequest and represents the request (on server) or response (on client).
Properties
message.headers
- Type:
message.method
- Type:
message.url
- Type:
message.statusCode
- Type:
message.statusMessage
- Type:
Methods
message.setTimeout(msecs[, callback])
msecscallback
message.socket.setTimeout(msecs, callback).
Class: http.ServerResponse
This object is created internally by an HTTP server and passed as the second parameter to the'request' event.
Methods
response.writeHead(statusCode[, statusMessage][, headers])
statusCodestatusMessageheaders
response.write(chunk[, encoding][, callback])
chunkencodingcallback- Returns:
response.end([data[, encoding]][, callback])
dataencodingcallback
response.setHeader(name, value)
namevalue
response.getHeader(name)
name- Returns:
response.removeHeader(name)
name
Properties
response.statusCode
- Type: Default:
200
response.statusMessage
- Type:
Class: http.ClientRequest
This object is created internally and returned fromhttp.request().
Events
Event: ‘response’
response
Event: ‘socket’
socket
Methods
request.write(chunk[, encoding][, callback])
chunkencodingcallback
request.end([data[, encoding]][, callback])
dataencodingcallback
request.setHeader(name, value)
namevalue
request.setTimeout(timeout[, callback])
timeoutcallback
socket.setTimeout() will be called.
HTTP Methods
http.get(url[, options][, callback])
urloptionscallback- Returns:
http.request(url[, options][, callback])
urloptionsmethodDefault:'GET'hostDefault:'localhost'portDefault:80pathDefault:'/'headers
callback- Returns:
HTTP Status Codes
Common Status Codes
200- OK201- Created204- No Content301- Moved Permanently302- Found304- Not Modified400- Bad Request401- Unauthorized403- Forbidden404- Not Found500- Internal Server Error502- Bad Gateway503- Service Unavailable