Node.js Web 模块

释放双眼,带上耳机,听听看~!

 

什么是 Web 服务器?

Web服务器一般指网站服务器,是指驻留于因特网上某种类型计算机的程序,Web服务器的基本功能就是提供Web信息浏览服务。它只需支持HTTP协议、HTML文档格式及URL,与客户端的网络浏览器配合。

大多数 web 服务器都支持服务端的脚本语言(php、python、ruby)等,并通过脚本语言从数据库获取数据,将结果返回给客户端浏览器。

 

目前最主流的三个Web服务器是Apache、Nginx、IIS。

Node.js Web 模块

 

 以下是演示一个最基本的 HTTP 服务器架构(使用 8080 端口),创建 server.js 文件,代码如下所示:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
1var http = require('http');
2var fs = require('fs');
3var url = require('url');
4
5
6// 创建服务器
7http.createServer(onRequest).listen(8080);
8
9// 控制台会输出以下信息
10console.log('Server running at http://127.0.0.1:8080/');
11
12function onRequest(request,response){
13  // 解析请求,包括文件名
14   var pathname = url.parse(request.url).pathname;
15  
16   // 输出请求的文件名
17   console.log("Request for " + pathname + " received.");
18  
19   // 从文件系统中读取请求的文件内容
20   fs.readFile(pathname.substr(1), function (err, data) {
21      if (err) {
22         console.log(err);
23         // HTTP 状态码: 404 : NOT FOUND
24         // Content Type: text/plain
25         response.writeHead(404, {'Content-Type': 'text/html'});
26      }else{            
27         // HTTP 状态码: 200 : OK
28         // Content Type: text/plain
29         response.writeHead(200, {'Content-Type': 'text/html'});    
30        
31         // 响应文件内容
32         response.write(data.toString());        
33      }
34      //  发送响应数据
35      response.end();
36   });
37}
38

接下来我们在该目录下创建一个 index.html 文件,代码如下:

 


1
2
3
4
5
6
7
8
9
10
11
12
1<!DOCTYPE html>
2<html>
3<head>
4<meta charset="utf-8">
5<title>测试</title>
6</head>
7<body>
8    <h1>我的第一个标题</h1>
9    <p>我的第一个段落。</p>
10</body>
11</html>
12

执行 server.js 文件:

接着我们在浏览器中打开地址:**http://127.0.0.1:8080/index.html**,显示如下图所示:

 Node.js Web 模块

 

使用 Node 创建 Web 客户端

Node 创建 Web 客户端需要引入 http 模块,创建 client.js 文件,代码如下所示:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
1var http = require('http');
2
3// 用于请求的选项
4var options = {
5   host: 'localhost',
6   port: '8080',
7   path: '/index.html'  
8};
9
10// 处理响应的回调函数
11var callback = function(response){
12   // 不断更新数据
13   var body = '';
14   response.on('data', function(data) {
15      body += data;
16   });
17  
18   response.on('end', function() {
19      // 数据接收完成
20      console.log(body);
21   });
22}
23// 向服务端发送请求
24var req = http.request(options, callback);
25req.end();
26

新开一个终端,执行 client.js 文件,输出结果如下:

Node.js Web 模块

 

给TA打赏
共{{data.count}}人
人已打赏
安全技术

RSA加密算法

2021-8-18 16:36:11

安全技术

C++ 高性能服务器网络框架设计细节

2022-1-11 12:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索