思路:
get和post:
想要在app.js里实现
app.get('/', function(req, res) {
res.send('首页');
})
这样就能配置路由的效果。
首先我们分析,app.js里的这种路由格式有两个参数,第一个参数是名字,第二个是真正要执行的动作函数。那么我们在routes.js中每次接收到这两个参数就注册一个路由,定义一个全局的对象G,G的下标是第一个参数即名字,内容便是第二个参数那个函数,这样每次有http请求的时候,都检查一下G的路由名字有没有被注册过,如果有的话直接跟前一讲一样执行即可。
有几个小细节:
- 把app.js里的http.creatorServer的参数/执行函数(我也不知道咋叫),直接放在了routes中,这样在app.js建立http服务的时候直接引入app即可,接受请求也在routes内完成,
- 由于分为get和post两种请求,所以开了
G._get
和G._post
两个全局变量,然后来请求的时候注意判断条件即可。 - 封装了res.writeHead,变成了send
静态web服务:
思路:在routes路由之前,加上配置静态web服务,获取地址,根据后缀找到对应的文件类型,如果找不到对应文件,那么才继续进行上面的get/post请求。
// app.js
const http = require('http');
const app = require('./module/routes');
const ejs = require('ejs');
// 注册 web 服务
http.createServer(app).listen(8081);
// 配置静态web服务
app.static('public');
// 配置路由
app.get('/', function(req, res) {
res.send('首页');
})
// 配置路由
app.get('/login', function(req, res) {
ejs.renderFile('./views/form.ejs', (err, data) => {
res.send(data);
})
})
// 配置路由
app.post('/doLogin', function(req, res) {
console.log(req.body);
res.send(req.body);
})
// 配置路由
app.get('/news', function(req, res) {
res.send('新闻');
})
// /module/routes.js
const url = require('url');
const fs = require('fs');
const path = require('path');
// 扩展res
function changeRes(res) {
res.send = (data) => {
res.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
res.end(data);
}
}
// 根据后缀名获取文件没醒
function getFileMime(extname) {
let data = fs.readFileSync('./data/mime.json');
let mimeObj = JSON.parse(data.toString());
return mimeObj[extname];
}
// 静态web服务方法
function initStatic(req, res, staticPath) {
// 1. 获取地址
let pathname = url.parse(req.url).pathname;
pathname = pathname=='/'?'/index.html':pathname;
let extname = path.extname(pathname);
// 2. 通过fs模块读取文件
// 同步方法
try {
let data = fs.readFileSync('./' + staticPath + pathname);
if (data) {
let mime = getFileMime(extname);
// console.log(' -' + extname + ' ' + mime);
res.writeHead(200, { 'Content-Type': '' + mime + ';charset="utf-8"' });
res.end(data);
}
} catch (err) {
}
}
let server = () => {
let G = {
// 区分 get 和 post
_get:{},
_post:{},
// 默认路径 静态web目录
staticPath: 'static'
};
let app = function(req, res) {
// 扩展res的方法
changeRes(res);
// 配置静态web服务
initStatic(req, res, G.staticPath);
let pathname = url.parse(req.url).pathname;
// 获取请求类型
let method = req.method.toLowerCase();
console.log(pathname);
if (G['_'+method][pathname]) {
if (method == "get") {
G._get[pathname](req, res);
} else {
console.log(`??`);
// post 获取post数据,把它绑定到req.body
let postData = '';
req.on('data', (chunk) => postData += chunk);
req.on('end', () => {
req.body = postData;
G._post[pathname](req, res);
})
}
} else {
res.writeHead(404, { 'Content-Type': 'text/html;charset="utf-8"' });
res.end('页面不存在');
}
}
app.get = function(str, cb) {
// 注册方法
G._get[str] = cb;
}
app.post = function(str, cb) {
// 注册方法
G._post[str] = cb;
console.log(str);
console.log(G._post['/doLogin']);
}
// 配置静态web服务目录
app.static = function(staticPath) {
G.staticPath = staticPath;
}
return app;
}
module.exports = server();
form.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ejs-login</title>
</head>
<body>
<form action='/doLogin' method='post'>
用户名:<input type="text" name='user'>
密码:<input type="password" name='password'>
<input type="submit">
</form>
</body>
</html>