HTTP服务器
要开发HTTP服务器程序,从头处理TCP连接,解析HTTP是不现实的。这些工作实际上已经由Node.js自带的http模块完成了。应用程序并不直接和HTTP协议打交道,而是操作http模块提供的request和response对象。
request对象封装了HTTP请求,我们调用request对象的属性和方法就可以拿到所有HTTP请求的信息。
response对象封装了HTTP响应,我们操作response对象的方法,就可以把HTTP响应返回给浏览器。
实例
http post请求的方法,实现一个模拟客户端发送post请求,提交数据,服务器接收数据并给客户端响应的功能。
服务器端代码 server.js
const http = require('http'); //引入http模块
http.createServer((request,response)=>{
request.on('data',(chunk)=>{
//打印客户端的请求数据
console.log('data:'+chunk);
});
request.on('end',()=>{
console.log(request.method); //客户端的请求方法
console.log(JSON.stringify(request.headers)); //客户端的请求头
console.log('recive request end');
});
request.on('close',()=>{
console.log('recive request close');
});
response.writeHead(200,{"Content-type":"text-plain;charset:UTF8"});//设置响应头
response.end("Hello,Node.js!"); //发送给客户端的响应数据
}).listen(3000);
console.log("Server Run");
这段代码主要是在3000端口启用服务器,在接收到请求之后,返回200状态码,并返回"Hello,Nodejs"文本。其中,request.on('data',(res)=>{...})是一个请求体数据到来时会触发的事件,事件会返回chunk参数,表示接受的数据。request.on('end',(res)=>{...})是请求体传输完毕会触发的事件。request.on('close',(res)=>{...})是用户请求结束时会触发的事件。接下来看客户端的代码。
客户端代码 client.js
const http = require('http');//引入http模块
const querystring = require('querystring');//引入querystring模块
let respData= ''; //用来获取响应数据
//要发送的请求数据,如果不使用querystring,也可以使用JSON.stringify
let data = querystring.stringify({
info:'hi',
test:5
});
const req = http.request({
//'hostname':'www.baidu.com',
'host': '127.0.0.1',
'port': 3000,
//'port':80,
'method': 'POST',
'headers': {
'Content-Type':'application/x-www-form-urlencoded',
'Content-Length': data.length
}
}, (res) => {
// console.log(res);
res.on('data', (chunk) => {
respData+= chunk;
});
res.on('end', () => {
console.log(respData);
console.log('request end...');
});
});
req.write(data);//发送请求数据
req.end();
req.on("error", function (err) {
console.log(err.message);
});
http.request是一个向服务端发起请求的方法,其中的配置字段有host(主机,例如127.0.0.1),hostname(域名),port(端口,默认80),method(请求方法,默认为GET),path(请求相对于根的路径,默认是'/'),headers等。其中该方法返回的方法中,可以用request.write()方法发送请求数据,并res.end()结束请求,应始终指定res.end()方法,不然不会获得返回。
测试 先启动server.js再启动client.js.
服务器端输出结果:
Server Run
data:info=hi&test=5
recive request close
POST
{"content-type":"application/x-www-form-urlencoded","content-length":"14","host":"127.0.0.1:3000","connection":"close"}
recive request end
客户端输出结果:
Hello,Node.js!
request end...
服务器端代码的另一种写法。 上例是使用createServer方法返回了一个http.Server对象,这其实是一个创建http服务的捷径,如果我们用以下代码来实现的话,也将一样可行,执行效果完全相同。
const http = require('http');
const server= new http.Server();
server.on("request",function(req,res){
req.on('data',(chunk)=>{
console.log('data:'+chunk);
});
req.on('end',()=>{
console.log(req.method);
console.log(JSON.stringify(req.headers));
console.log('recive request end');
});
req.on('close',()=>{
console.log('recive request close');
});
res.writeHead(200,{
"content-type":"text/plain;charset=utf-8"
});
res.write("Hello,Node.js!");
res.end();
});
server.listen(3000);
console.log("Server Run");