详解Node.js API系列 Http模块(1) 构造一个简单的静态页服务器

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

HTTP

http api的文档翻译得太无聊了,很多用不上,例子太少,翻译到一半就觉得受不了,决定放弃,决定,用另外一种方式去介绍这部分的API。http模块,主要的应用是两部分,一部分是http.createServer 担当web服务器,另一部分是http.createClient,担当客户端,实现爬虫之类的工作。从这两方面着手介绍HTTP api。下文将会介绍http.createServer部分。

设计目标

实现一个静态页服务器

目标功能

  • url解析
  • 500页面,404页面回复
  • 读取路径目录下的静态页文件

最简单的web服务器


1
2
3
4
5
6
7
1var http = require('http');
2http.createServer(function (request, response) {
3  response.writeHead(200, {'Content-Type': 'text/plain'});
4  response.end('Hello World\n');
5}).listen(1337, '127.0.0.1');
6console.log('Server running at http://127.0.0.1:1337/');
7

浏览器输入http://127.0.0.1:1337/,将会看到熟悉的hello world


1
2
1response.writeHead(200, {'Content-Type': 'text/plain'});
2
  • writeHead,200表示页面正常,text/plain表示是文字。
  • write 写入网页内容。
  • end 完成写入。

创建HTTP代理http.createServer,返回代理对象,通过返回的对象可以进行

事件监听


1
2
3
4
5
6
7
8
1proxy = http.createServer()
2proxy.on('connect')    
3proxy.on('upgrade')
4proxy.on('close')
5proxy.on('socket')
6proxy.on('response')
7proxy.on('checkContinue')
8

http.createServer 回调返回 req 和 res 对象

requestd对象

  • request.url

客户端请求的url地址,如http://127.0.0.1/hello/world,那么request.url就是/hello/world

  • request.headers

客户端请求的http header

  • request.method

获取请求的方式,一般有几个选项,POST,GET和DELETE等,服务器可以根据客户端的不同请求方法进行不同的处理。

response对象

  • response.writeHead(statusCode, [reasonPhrase], [headers])

statusCode html页面状态值
header 返回的http header,可以是字符串,也可以是对象

response.setTimeout(msecs, callback)

设置http超时返回的时间,一旦超过了设定时间,连接就会被丢弃

  • response.statusCode

设置返回的网页状态码

  • response.setHeader(name, value)

设置http协议头

  • response.headersSent

判断是否设置了http的头

  • response.write(chunk, [encoding])

返回的网页数据,[encoding] 默认是 utf-8

  • response.end([data], [encoding])

将设置的数据包,发送数据到客户端。

博客地址:http://blog.whattoc.com/2013/09/15/nodejs_http1/

url解析


1
2
3
4
5
6
7
8
9
10
11
12
1                          url.parse(string).query
2                                       |
3           url.parse(string).pathname  |
4                       |               |
5                       |               |
6                     ------     ---------------
7http://localhost:8888/start?foo=bar&hello=world
8        --------------      
9              |
10              |
11       req.header.host      
12

错误页面设计

500页面


1
2
3
4
5
6
7
8
9
10
1var page_500 = function(req, res, error){
2    res.writeHead(500, {
3      'Content-Type': 'text/html'
4    });
5    res.write('<!doctype html>\n');
6    res.write('<title>Internal Server Error</title>\n');
7    res.write('<h1>Internal Server Error</h1>');
8    res.write('<pre>' + util.inspect(error) + '</pre>');
9}
10

404页面


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1var page_404 = function(req, res, path){
2    res.writeHead(404, {
3      'Content-Type': 'text/html'
4    });
5    res.write('<!doctype html>\n');
6    res.write('<title>404 Not Found</title>\n');
7    res.write('<h1>Not Found</h1>');
8    res.write(
9    '<p>The requested URL ' +
10     path +
11    ' was not found on this server.</p>'
12    );
13    res.end();
14}
15

读取网页文件


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
1var mimetype = {
2  'txt': 'text/plain',
3  'html': 'text/html',
4  'css': 'text/css',
5  'xml': 'application/xml',
6  'json': 'application/json',
7  'js': 'application/javascript',
8  'jpg': 'image/jpeg',
9  'jpeg': 'image/jpeg',
10  'gif': 'image/gif',
11  'png': 'image/png',
12  'svg': 'image/svg+xml'
13}
14
15var fs = require('fs');
16fs.exists(realPath, function(exists){
17    if(!exists){
18
19        return page_404(req, res, pathname);
20
21    } else {
22        var file = fs.createReadStream(realPath);
23
24        res.writeHead(200, {
25            'Content-Type': mimetype[realPath.split('.').pop()] || 'text/plain'
26        });
27
28        file.on('data', res.write.bind(res));
29        file.on('close', res.end.bind(res));
30        file.on('error', function(err){
31            return page_500(req, res, err);
32        });
33    }
34});
35

完整静态服务器代码

项目地址:https://github.com/youyudehexie/node-webstatic


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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
1var http = require('http');
2var url = require('url');
3var fs = require('fs');
4var util = require('util');
5var mimetype = {
6  'txt': 'text/plain',
7  'html': 'text/html',
8  'css': 'text/css',
9  'xml': 'application/xml',
10  'json': 'application/json',
11  'js': 'application/javascript',
12  'jpg': 'image/jpeg',
13  'jpeg': 'image/jpeg',
14  'gif': 'image/gif',
15  'png': 'image/png',
16  'svg': 'image/svg+xml'
17}
18var page_404 = function(req, res, path){
19    res.writeHead(404, {
20      'Content-Type': 'text/html'
21    });
22    res.write('<!doctype html>\n');
23    res.write('<title>404 Not Found</title>\n');
24    res.write('<h1>Not Found</h1>');
25    res.write(
26    '<p>The requested URL ' +
27     path +
28    ' was not found on this server.</p>'
29    );
30    res.end();
31}
32var page_500 = function(req, res, error){
33    res.writeHead(500, {
34      'Content-Type': 'text/html'
35    });
36    res.write('<!doctype html>\n');
37    res.write('<title>Internal Server Error</title>\n');
38    res.write('<h1>Internal Server Error</h1>');
39    res.write('<pre>' + util.inspect(error) + '</pre>');
40}
41http.createServer(function (req, res) {
42
43    var pathname = url.parse(req.url).pathname;
44    var realPath = __dirname +  "/static" + pathname;
45    fs.exists(realPath, function(exists){
46    if(!exists){
47        return page_404(req, res, pathname);
48    } else {
49        var file = fs.createReadStream(realPath);
50
51            res.writeHead(200, {
52               'Content-Type': mimetype[realPath.split('.').pop()] || 'text/plain'
53            });
54        file.on('data', res.write.bind(res));
55        file.on('close', res.end.bind(res));      
56        file.on('error', function(err){
57        return page_500(req, res, err);
58        });
59    }    
60    });  
61}).listen(1337, '127.0.0.1');
62console.log('Server running at http://127.0.0.1:1337/');
63

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

base64加密解密

2021-8-18 16:36:11

安全技术

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

2022-1-11 12:36:11

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