Node.js的http模块:创建HTTP服务器、客户端示例
新书速览|Vue.js+Node.js全栈开发实战-CSDN博客《Vue.js+Node.js全栈开发实战(第2版)(Web前端技能丛书)》(王金柱)【择要 书评 试读】- 京东图书 (jd.com)
要使用http模块,只必要在文件中通过require('http')引入即可。http模块是Node.js原生模块中最为亮眼的模块。传统的HTPP服务器会由Apache、Nginx、IIS之类的软件来担任,但是Node.js并不必要。Node.js的http模块本身就可以构建服务器,而且性能非常可靠。
1.Node.js服务器端
下面创建一个简朴的Node.js服务器。
【代码4-4】
01const http = require('http');
02const server = http.createServer(function(req, res) {
03 res.writeHead(200,{
04 'content-type': 'text/plain'
05 });
06 res.end('Hello, Node.js!');
07});
08server.listen(3000, function() {
09 console.log('listening port 3000');
10});
【代码阐明】
[*]运行这段代码,在浏览器中打开http://localhost:3000/或者http://127.0.0.1:3000/,页面中显示“Hello,Node.js!”笔墨。
http.createServer()方法返回的是http模块封装的一个基于变乱的HTTP服务器。同样地,http.request是其封装的一个HTTP客户端工具,可以用来向HTTP服务器发起请求。上面的req和res分别是http.IncomingMessage和 http.ServerResponse的实例。
http.Server的变乱重要有:
[*]request:最常用的变乱,当客户端请求到来时,该变乱被触发,提供req和res两个参数,表示请求和响应信息。
[*]connection:当TCP毗连创建时,该变乱被触发,提供一个socket参数,是net.Socket的实例。
[*]close:当服务器关闭时,触发变乱(注意,不是在用户断开毗连时)。
http.createServer()方法其实就是添加了一个request变乱监听,利用下面的代码同样可以实现【代码4-4】的效果。
【代码4-5】
01const http = require('http');
02const server = new http.Server();
03server.on('request', function(req, res) {
04 res.writeHead(200,{
05 'content-type': 'text/plain'
06 });
07 res.end('Hello, Node.js!');
08});
09server.listen(3000, function() {
10 console.log('listening port 3000');
11});
http.IncomingMessage是HTTP请求的信息,提供了以下3个变乱:
data:当请求体数据到来时该变乱被触发。该变乱提供一个chunk参数,表示吸取的数据。
end:当请求体数据传输完毕时,该变乱被触发,此后不会再有数据。
close:用户当前请求结束时,该变乱被触发。
http.IncomingMessage提供的重要属性有:
method:HTTP请求的方法,如GET。
headers:HTTP请求头。
url:请求路径。
httpVersion:HTTP协议的版本。
将上面提到的知识融合到【代码4-4】的服务器代码中。
【代码4-6】
01const http = require('http');
02const server = http.createServer(function(req, res) {
03 let data= '';
04 req.on('data', function(chunk) {
05 data += chunk;
06 });
07 req.on('end', function() {
08 let method = req.method;
09 let url = req.url;
10 let headers = JSON.stringify(req.headers);
11 let httpVersion = req.httpVersion;
12 res.writeHead(200,{
13 'content-type': 'text/html'
14 });
15 let dataHtml = '<p>data:' + data + '</p>';
16 let methodHtml = '<p>method:' + method + '</p>';
17 let urlHtml = '<p>url:' + url + '</p>';
18 let headersHtml = '<p>headers:' + headers + '</p>';
19 let httpVersionHtml = '<p>httpVersion:' + httpVersion + '</p>';
20let resData=dataHtml + methodHtml + urlHtml + headersHtml + httpVersionHtml;
21 res.end(resData);
22 });
23});
24server.listen(3000, function() {
25 console.log('listening port 3000');
26});
打开浏览器输入地址后,可以在浏览器页面中看到如图4.9所示的信息。
https://i-blog.csdnimg.cn/direct/176e4e940ae441bba5f1364b176ac457.png
图4.9 浏览器效果
http.ServerResponse是返回给客户端的信息,其常用的方法为:
[*]res.writeHead(statusCode,):向请求的客户端发送响应头。
[*]res.write(data,):向请求发送内容。
[*]res.end(,):结束请求。
这些方法在上面的代码中已经演示过了,这里就不再演示了。
2.客户端向HTTP服务器发起请求
客户端向HTTP服务器发起请求的方法有:
[*]http.request(option[,callback]):option为json对象,重要字段有host、port(默认为80)、method(默认为GET)、path(请求的相对于根的路径,默认是“/”)、headers等。该方法返回一个httpClientRequest实例。
[*]http.get(option[,callback]):http.request()使用HTTP请求方式GET的轻便方法。
同时运行【代码4-4】和【代码4-7】中的代码,可以发现命令行中输出“Hello, Node.js!”字样,表明一个简朴的GET请求发送乐成了。
【代码4-7】
01const http = require('http');
02let reqData = '';
03http.request({
04 'host': '127.0.0.1',
05 'port': '3000',
06 'method': 'get'
07}, function(res) {
08 res.on('data', function(chunk) {
09 reqData += chunk;
10 });
11 res.on('end', function() {
12 console.log(reqData);
13 });
14}).end();
利用http.get()方法也可以实现同样的效果。
【代码4-8】
01const http = require('http');
02let reqData = '';
03http.get({
04 'host': '127.0.0.1',
05 'port': '3000'
06}, function(res) {
07 res.on('data', function(chunk) {
08 reqData += chunk;
09 });
10 res.on('end', function() {
11 console.log(reqData);
12 });
13}).end();
与服务端一样,http.request()和http.get()方法返回的是一个http.ClientRequest()实例。http.ClientRequest()类重要的变乱和方法有:
[*]response:当吸取到响应时触发。
[*]request.write(chunk[,encoding][,callback]):发送请求数据。
[*]res.end([,encoding][,callback]):发送请求完毕,应该始终指定这个方法。
同样可以改写【代码4-8】为【代码4-9】。
【代码4-9】
01const http = require('http');
02let reqData = '';
03let option= {
04 'host': '127.0.0.1',
05 'port': '3000'
06};
07const req = http.request(option);
08req.on('response', function(res) {
09 res.on('data', function(chunk) {
10 reqData += chunk;
11 });
12 res.on('end', function() {
13 console.log(reqData);
14 });
15});
https://i-blog.csdnimg.cn/direct/0f8317b991c44242b93897faa553c4d0.jpeg
https://i-blog.csdnimg.cn/direct/e8f9cadae18549c481070cb7fac718c8.jpeg
https://i-blog.csdnimg.cn/direct/25112350b2df4a44b84ff2aadcd49ed4.jpeg
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]