Node(9) HTTP

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)

http.get(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!



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值