nodejs 中,通过路由读取html页面,并在客户端显示出来

1、html页面代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
ul li{
float: left;
200px;
height: 50px;
text-align: center;
list-style: none;
border: 0.1px solid #000;
line-height: 50px;
color:#fff;
}
.red{
background: red;
}
.blue{
background: blue;
}
.green{
background: green;
}
</style>
</head>
<body>
<ul>
<li class="red">1</li>
<li class="blue">2</li>
<li class="green">3</li>
</ul>
</body>
</html>

2、nodejs 代码:

************************创建服务器**************************

var http=require("http");
var url=require("url");
var router=require("./02.js")
http.createServer(function(req,res){
if(req.url!="/favicon.ico"){
console.log("33")
console.log(req.url)
pathname=url.parse(req.url).pathname;
pathname=pathname.replace(///,"");
try{
console.log("22")
router[pathname](req,res);
console.log(pathname);
console.log("00")
}catch(e){
console.log("11")
console.log(e)
}
}
}).listen(8000);
console.log("server running at http://127.0.0.1:8000/")

**********************************路由控制器并显示在客户端**************************************

var optfile=require("./03.js")
module.exports={
login:function(req,res){
res.writeHead(200,{"Content-Type":"text/html",charset:'utf-8'});

function recall(data){
res.write(data);
res.end("");
}
optfile.readfile("index.html",recall);
}
}

**************************************异步读取文档***********************************************

var fs=require("fs");
module.exports={
readfile:function(path,recall){
fs.readFile(path,function(err,data){
if(err){
console.log("不对");
recall("没有找到页面!");
}else{
console.log(data.toString());
recall(data);
}
})
}
}

3、注意事项:

①通过路由控制器跳转:

  pathname=url.parse(req.url).pathname;
  pathname=pathname.replace(///,"");

  router[pathname](req,res);

  避免二次运行,添加一个if判断(if(req.url!="/favicon.ico"));

②当读取的html页面带有src等链接时,程序会自动再次请求服务器,进行运行!

原文地址:https://www.cnblogs.com/pyj63/p/8042068.html