HTTP server
we can simply create a http server:
var http = require('http');
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<h1>Node.js</h1>');
res.end('<p>Hello World</p>');
}).listen(3000);
console.log("HTTP server is listening at port 3000.");
http.Server events
-
request
: when client request comes, this event will be triggered, it provide 2 parameters: req and res, they are the instances of http.ServerRequest and http.ServerResponse. Stand for request and response. -
connection
: when TCP connection established, this event will be triggered, it provide one parameter: socket, is instance of net.Socket. this event is more coarse-grained(粗粒度) than request, because in Keep-Alive mode, there may be many requests in a same connection. -
close
: when server closed, this event will be triggered. Please notice it is not when user disconnect the connection.
http.ServerRequest
HTTP request commonly contains 2 parts: Request Header and Request Body.
http.ServerRequest also provide 3 events to control Request Body transmission.
-
data
: when Request Body data comes, this event will be triggered, this event provide a parameter: chunk, stand for data received. -
end
: when Request Body data transmission complete, this event will be triggered, data will never comes later. -
close
: when user's current request ended, this event will be triggered.
ServerRequest properties
-
complete
: whether client complete current send -
httpVersion
: http protocol version, 1.0 or 1.1 -
method
: http request method, e.g. GET/ POST/ PUT/ DELETE -
url
: original request path, e.g. /static/image/icon.png -
headers
: http request header -
trailers
: http request trailer, uncommon -
connection
: current http connection socket, instance of net.Socket -
socket
: alias of connection -
client
: alias of socket
fetch contents of GET request
GET request can pass parameters followed by path, url
module in Node.js provide a function called parse
, can parse url
var http = require('http');
var url = require('url');
var util = require('util');
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(util.inspect(url.parse(req.url, true)));
}).listen(3000);
//result:
// Url {
// protocol: null,
// slashes: null,
// auth: null,
// host: null,
// port: null,
// hostname: null,
// hash: null,
// search: '?name=realank&email=realank@126.com',
// query: { name: 'realank', email: 'realank@126.com' },
// pathname: '/user',
// path: '/user?name=realank&email=realank@126.com',
// href: '/user?name=realank&email=realank@126.com' }
fetch contents of POST request
waiting for Request Body is a waste of time, so by default, Node.js won't parse Request Body, if we need, we can do it by hand
//httpserverrequestpost.js
var http = require('http');
var querystring = require('querystring');
var util = require('util');
http.createServer(function(req, res) {
var post = '';
req.on('data', function(chunk) {
post += chunk;
});
req.on('end', function() {
post = querystring.parse(post);
res.end(util.inspect(post));
});
}).listen(3000);
http.ServerResponse
It have 3 important functions
-
response.writeHead(statusCode, [headers])
: send response header to request client. statusCode is HTTP status code, e.g. 200 (success), 404(not found). headers is a object like associate array, stand for every property of response header. This function can be invoked only once. If it is not invoked, response header will be generated automatically. -
response.write(data, [encoding])
: send response contents to request client. data is a Buffer instance or a string. If data is a string, you should set encoding, by default, it is utf-8. This function can be invoked many times, before respond.end. -
response.end([data], [encoding])
: end response. This function must be invoked once.
var http = require('http');
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<h1>Node.js</h1>');
res.end('<p>Hello World</p>');
}).listen(3000);
console.log("HTTP server is listening at port 3000.");
HTTP client
http module provide 2 functions, http.request and http.get.
http.request(options, callback)
option
is a object like associate array, stand for parameters of request.
callback
is the callback function of request.
commonly used parameters of option:
-
host
: host name or ip address of request website -
port
: port of request website, default is 80 -
method
: request method, default is GET -
path
: request path related to root path, default is '/', QuertyString should be included, e.g. /search?name=realank -
headers
: a associated array object, is the content of Request Header
callback passes a parameter, is a instance of http.ClientResponse.
http.request returns a instance of http.ClientRequest
//httprequest.js
var http = require('http');
var querystring = require('querystring');
var contents = querystring.stringify({
name: 'realank',
email: 'realank@126.com',
address: 'Tianjin',
});
var options = {
host: '127.0.0.1',
path: '/',
port: 3000,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length' : contents.length
}
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (data) {
console.log(data);
});
});
req.write(contents);
req.end();
http.get(options, callback)
the simplified version of http.request, dedicated to GET request.
var http = require('http');
http.get({host: '127.0.0.1',port: 3000}, function(res) {
res.setEncoding('utf8');
res.on('data', function (data) {
console.log(data);
});
});
1.http.ClientRequest
Instance of http.ClientRequest will be returned by http.request or http.get, stand for a ongoing HTTP request that has been established. It provide a response event.
var http = require('http');
var req = http.get({host: '127.0.0.1',port: 3000});
req.on('response', function(res) {
res.setEncoding('utf8');
res.on('data', function (data) {
console.log(data);
});
});
http.ClientRequest also provide functions blow:
-
request.abort()
: abort sending current request -
request.setTimeout(timeout, [callback])
: set timeout interval, in ms.
2.http.ClientResponse
It provide 3 events. data
, end
, close
.
data event pass a parameter called chunk
.
It also provide these properties:
-
statusCode
: http status code, 200, 404, 500 -
httpVersion
: http protocol version, 1.0 or 1.1 -
headers
: http request header -
trailers
: http request trailer (uncommon)
it provide these functions:
-
response.setEncoding([encoding])
: set default encoding, null means no encoding(Buffer style) -
response.pause()
: pause receive data and send event, to achieve download function -
response.resume()
: resume from pause