用原生nodejs封装类似于express的路由以及静态资源服务器
-
用原生nodejs来实现express的路由、静态资源服务;对express这些框架不再陌生
项目目录:

data:存放静态数据文件
data/mime.json 文件后缀对应的文件类型
module:模块目录
module/router.js :路由模块
public:静态资源目录
views:页面文件夹
views/form.ejs:一个简易的登录提交页面
01_exoress_router.js:项目入口
具体代码:
01_exoress_router.js 项目入口:
const http = require('http');
const app = require("./module/router")
const ejs = require("ejs");
// 注册web服务
http.createServer(app).listen(3000);
// 修改静态web目录
app.static("public")
// 注册路由
app.get("/",(req,res) => {
res.send('首页');
})
app.get("/login",(req,res) => {
ejs.renderFile("./views/form.ejs",{},{},(err,data) => {
res.send(data);
})
})
app.post("/doLogin",(req,res) => {
console.log(req.body);
res.send(req.body);
})
console.log('Server running at http://127.0.0.1:3000/');
module/router.js :
const fs = require("fs");
const path = require('path');
const url = require('url');
// 拓展res方法
function changeRes(res){
res.send = (data) => {
res.writeHead(200, {'Content-Type': 'text/html;charset="utf-8"'});
res.end(data);
}
}
// 根据后缀名获取文件类型
let getFileMime = function (extname) {
var data = fs.readFileSync("./data/mime.json");//这里的路径是相对于app的
let mime = JSON.parse(data.toString());
return mime[extname];
}
// 静态web服务的方法
function initStatic(req,res,staticPath){
// 获取地址
let pathname = url.parse(req.url).pathname;
pathname = pathname == '/' ? '/index.html' : pathname;
// 可以获取后缀名path.extname()
let extname = path.extname(pathname);
// 通过fs模块读取文件
if(pathname != '/favicon.ico'){//过滤掉/favicon.ico路径
try {
let data = fs.readFileSync(`./${staticPath}` + pathname);
if(data){
let mime = getFileMime(extname);
res.writeHead(200, {'Content-Type': `${mime};charset="utf-8"`});
res.end(data);
}
} catch (error) {
}
}else{
res.end()
}
}
let server = function(){
let G = {
_get:{},
_post:{},
staticPath:'static', //默认静态资源目录是 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();
if(G['_'+method][pathname]){
if(method == 'get'){
// get
G._get[pathname](req,res);
}else{
// 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('页面不存在');
}
}
// 注册 get方法
app.get = function(str,cb){
G._get[str] = cb;
}
// 注册post方法
app.post = function(str,cb){
G._post[str] = cb;
}
// 配置静态web目录
app.static = function(staticPath){
G.staticPath = staticPath;
}
return app;
}
module.exports = server();
views/form.ejs:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="./css/style.css"> </head> <body> <h2>登录页面</h2> <form action="/doLogin" method="post"> 用户名:<input type="text" name="username"/> <br> <br> 密码:<input type="password" name="password"/> <br> <br> <input type="submit" value="提交"> </form> </body> </html>
-

浙公网安备 33010602011771号