router-lxc
Version:
router封装 简易版
100 lines (79 loc) • 2.76 kB
JavaScript
const url = require("url");
const fs = require("fs");
const path = require("path");
const qs = require("querystring")
//收集事件
const routerMap = {
get:{},
post:{}
}
const router = function(req,res){
//给res添加一个json方法
res.json = function(obj){
res.end(JSON.stringify(obj))
}
//处理静态资源
handleStatic(req,res);
//获取用户请求的方式
var method = req.method.toLowerCase();
//获取用户请求的地址
var {pathname,query} = url.parse(req.url,true);
if(method === "get"){
if(routerMap.get[pathname]){
//将query的值赋值给req.query
req.query = query;
routerMap.get[pathname](req,res)
}else{
res.end("404")
}
}else if(method === "post"){
if(routerMap.post[pathname]){
var str = "";
//获取post传递的参数
req.on("data",(data)=>{
str += data;
})
req.on("end",()=>{
str = decodeURIComponent(str);
console.log(str);
// req.body = str;
req.body = qs.parse(str);
routerMap.post[pathname](req,res)
})
}
}
}
//注册事件
router.get = function(path,callback){
routerMap.get[path] = callback;
}
//注册事件
router.post = function(path,callback){
routerMap.post[path] = callback;
}
//处理所有的静态资源访问
function handleStatic(req,res){
var {pathname} = url.parse(req.url,true);
//获取文件的后缀
var ext = pathname.substring(pathname.lastIndexOf("."));
if(pathname ==="/"){
res.writeHead(200,{"content-type":"text/html;charset=utf8"});
res.end(getFile(path.join(__dirname,"../public/index.html")))
}else if(ext === ".css"){
res.writeHead(200,{"content-type":"text/css;charset=utf8"});
res.end(getFile(path.join(__dirname,"../public",pathname)));
}else if(ext === ".js"){
res.writeHead(200,{"content-type":"application/x-javascript;charset=utf8"});
res.end(getFile(path.join(__dirname,"../public",pathname)));
}else if(/.*\.(jpg|png|gif)/.test(ext)){
res.writeHead(200,{"content-type":`image/${RegExp.$1};charset=utf8`});
res.end(getFile(path.join(__dirname,"../public",pathname)));
}else if(ext === ".html"){
res.writeHead(200,{"content-type":"text/html;charset=utf8"});
res.end(getFile(path.join(__dirname,"../public",pathname)));
}
}
function getFile(filePath){
return fs.readFileSync(filePath);
}
module.exports = router;