http is the core object in Node.
main objects:
http - can create a Server object, common methods: createServer(), get() and request().
http.Server - server can be created by http. common methods: listen()
http.ServerRequest - inherited from ReadableStream, event: data, end. method: setEncoding() property: url, method,
http.ServerResponse - inherited from WritableStream, you can construct the response using writeHead() and write() method. use end() to send data.
CreateServer()
http.createServer([requestListener])
creates a server object. requestListener is the function that is taken when request event occurs.
requestListener is of the form:
function (request, response) { }
http making individual request - useful for web services!
There is a request method for http object used for making a http request
http.request(options, callback)
options specifies the details of the request, options are automatically parsed by url.parse() method
callback specifies the action to take when the request is send.
example from node.js document:
var http = require( 'http' );
var options={
host:'www.google.com',
port: 80,
method: 'GET'
};
var req = http.request( options, function( res ){
console.log('STATUS: ' + res.statusCode );
console.log( 'HEADERS: ' + JSON.stringify(res.headers ));
res.setEncoding( 'utf8');
res.on( 'data', function( chunk ){
console.log( 'BODY: ' + chunk );
});
});
req.on('error', function(e){
console.log( 'problem with request: ' + e.message );
});
req.write( 'data\n');
req.end(); //send the data
The server console will get google's homepage html code.
if res.setEncoding( 'utf8‘ ) is omitted, the data will not be interpreted correctly!