node HTTP服务器和HTTP客户端

1,093 阅读3分钟

##一、HTTP服务器 ####1.http.server 的事件 http.server 实现了,它提供了一套封装级别很低的API,仅仅是流控制和简单的解析,所有的高层功能都需要通过它的接口来实现。

//引入模块
var http=require('http');
http.createServer(function(req,res){
	res.writeHead(200,{'Conten-Type':'text/html'});
	res.write('<h1>Hello world</h1>');
	res.end('<p>PACTH</p>');
}).listen(3000);

console.log('http server is listening at port 3000');

connection:当TCP连接建立时,该事件被触发,提供一个参数socket,
为net.Socket的实例(底层协议对象)

close:当服务器关闭时,该事件被触发。
除此之外还有checkContinue,upgrade,clientError事件。



####2.http.ServerRequest 请求的信息 此对象是后端开发者最关注的内容,它一般由http.Server的request 事件发送,作为第一个参数发送,通常写为request 或req。

HTTP请求分为两部分:请求头和请求体。请求内容短的可以直接在请求头解析完后立即读取,而请求体可能体比较长,需要一定的事件传输就比较久,因此就会有3个事件用于控制请求体传输。

1.  data:当请求体数据到来时,该事件被触发,该事件一共一个参数chunk,表示接受到的数据。
2. end:当请求体数据完成传输时,该事件被触发,此后将不会再有数据到来。
3.  close :当用户当前请求结束时,该事件被触发,不同于end,
    如果强制终止了传输,也会触发close。

####3.处理get请求

//引入模块
var http = require('http');
var urls = require('url');
var util = require('util');

//创建服务
http.createServer(function(req,res){
	res.writeHead(200,{'Content-Type':'text/plan'});
        //解析打印成字符串返回给客户端。
	res.end(util.inspect(urls.parse(req.url,true)));
}).listen(3000);

效果如下:


Paste_Image.png


思路:通过判断url过来的的值分配不同的路由。


####4.处理post请求

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请求格式
		//相当于Ext.decode()
		post =querystring.parse(post);
		//向前端返回
		res.end(util.inspect(post));
	})

}).listen(3000);

模拟post请求:

Paste_Image.png


请求结果:

Paste_Image.png


##二、HTTP客户端 ######2.1、http客户端请求服务器数据 例子:模拟一个http客户端,请求数据,服务器返回数据

var http =require('http');
var querystring=require('querystring');

http.createServer(function(req,res){
	var post='';
	req.on('data',function(chunk){
		post+=chunk;
	});
	req.on('end',function(){
		post=querystring.parse(post);
		console.log('参数解析完成,返回name参数 + age + address');
		res.end(post.name+'  '+post.age+' '+post.address);
	});
}).listen(3000);

//客户端请求
var contents = querystring.stringify({
	name:'can',
	age:23,
	address:'shenzhen'
});

//声明请求参数
var options = {
	host :'localhost',
	path:'/',
	port:3000,
	method:'POST',
	headers:{
		'Content-Type':'application/x-www-form-url-urlencoded',
		'Content-Length':contents.length
	}
};


//发送请求
var req=http.request(options,function(res){
	res.setEncoding('utf-8');
	res.on('data',function(data){
		console.log('后台返回数据');
		console.log(data);
	});
});

req.write(contents);
//调用end,否则会一直停留在请求状态
req.end();


####2.2http客户端请求 为了便于简化请求方式,http 模块提供了一个方便的接口,http.get();

var http = require('http');
var url = require('url');
var util = require('util');

http.createServer(function(req,res){
	console.log('请求到来,解析参数');
	var params=url.parse(req.url,true);
	console.log('解析完成');
	console.log(util.inspect(params));
	console.log('向客户端返回');
	res.end(params.query.name+ '  '+params.query.age);
}).listen(3000);


http.get({
	'host':'localhost',
	path:'/user?name=can&age=23',
	port:3000},function(res){
		res.setEncoding('utf-8');
		res.on('data',function(data){
			console.log('服务器相应回来的数据为:'+data);
		})
})


Paste_Image.png