封装路由

1.路由的封装

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
const fs = require('fs');
const path = require('path');
const url = require('url');
const ejs = require('ejs');

// 私有方法
let getMime = (extName) => {
let data = fs.readFileSync('./data/mime.json');
let mimeObj = JSON.parse(data.toString());
return mimeObj[extName];
}
// 封装路由
let app = {
static(req, res, staticPath) {
//获取url中的路径(pathname)
let pathname = url.parse(req.url).pathname;
// 获取路径中的后缀名
let extName = path.extname(pathname);
pathname = pathname == '/' ? '/index.html' : pathname;

// 获得正确的路径
if (pathname != '/favicon.ico') {
try {
// 读取对应文件夹下的文件并传给浏览器
let data = fs.readFileSync('./' + staticPath + pathname);
if (data) {
// 获取对应后缀名的响应头
let mimeName = getMime(extName);
res.writeHead(200, { 'Content-Type': '' + mimeName + ';charset=utf-8' });
res.end(data);
}
} catch (error) {
}
}
},
login(req,res){
res.end("login");
},
news(req,res){
res.end("news");
},
form(req,res){
ejs.renderFile('./views/form.ejs',{},(err,data)=>{
res.writeHead(200,{'Content-Type':'text/html,charset="utf-8"'});
res.end(data);
})
},
doLogin(req,res){
let postData = '';
req.on('data',(chunk)=>{
postData += chunk;
})
req.on('end',()=>{
console.log(postData);
res.end(postData);
})
},
error(req,res){
res.end("error");
}
}
module.exports = app;

2.使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const http = require('http');
const routes = require('./module/routes');
const url = require('url');

http.createServer((req,res)=>{
// 创建静态web服务
routes.static(req,res,'state');
// 获取请求类型
// console.log(req.method);
// 路由
let pathname = url.parse(req.url).pathname.replace("/","");

try {
routes[pathname](req,res);
} catch (error) {
routes['error'](req,res);
}


}).listen(8080);
console.log("http://127.0.0.1:8080");

Comments