一、常规路由提取
const http=require("http");
const ejs=require("ejs");
const url=require("url");
let port=80;
let host="localhost";
let router=require("./router");
let app=http.createServer((req,res)=>{
res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});
let path=url.parse(req.url).pathname;
if(path!="/favicon.ico")
{
if(path=="/")
{
path="home";
}
else if(path=="/login")
{
path="login";
}
router[path](req,res);
}
});
app.listen(port,host,()=>{
console.log(`http://${host}:${port}`);
});
let router={
'home':(req,res)=>{
res.end("首页");
},
'login':(req,res)=>{
res.end("登录界面");
}
}
module.exports=router;
二、模拟express框架来建立服务
const http=require("http");
const ejs=require("ejs");
let port=8080;
let host="localhost";
let app=require("./router");
http.createServer(app).listen(port,host);
app.get("/",(req,res)=>{
console.log(req.query);
res.send("首页")
});
app.get("/login",(req,res)=>{
console.log(req.query);
res.send("登录界面");
});
app.get("/regest",(req,res)=>{
console.log(req.query);
ejs.renderFile("./view/regest.ejs",(err,html)=>{
if(err)
{
throw err;
}
res.send(html);
});
});
app.post("/doregest",(req,res)=>{
console.log(req.body);
res.send("注册");
});
const url=require("url");
let obj={
_get:{},
_post:{}
};
let app=function(req,res){
res.send=function(data){
res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});
res.end(data);
}
let path=url.parse(req.url,true);
let pathname=path.pathname;
let method=req.method.toLowerCase();
if(pathname=="/favicon.ico") return;
if(obj['_'+method][pathname]){
if(method=="get"){
let params=path.query;
req.query=params;
obj['_'+method][pathname](req,res);
}
else{
let data="?";
req.on("data",(info)=>{
data+=info;
});
req.on("end",()=>{
req.body=url.parse(data,true).query;
obj['_'+method][pathname](req,res);
})
}
}
else{
res.end("404");
}
}
app.get=function(string,callback){
obj._get[string]=callback;
}
app.post=function(string,callback){
obj._post[string]=callback;
}
module.exports=app;
<body>
<form action="doregest" method="POST">
<ul>
<li>用户名:<input type="text" name="username"></li>
<li>密码:<input type="text" name="userpwd"></li>
<li><button>注册</button></li>
</ul>
</form>
</body>