node路由搭建

server.js


var http = require("http");
var router = require("./router.js");
//var url = require("url");
var server = http.createServer(function(req,res){
	if(req.url != "/favicon.ico"){
	   //console.log(req.url)
	   
		var surl = req.url.slice(1);//url.parse(req.url).pathname.replace(/\//,"")
         
		res.writeHead(200,{"content-type":"text/html;charset=utf-8","Access-Control-Allow-Origin":"*"});
		try{
			router[surl](req,res);	
		}catch(e){
			router["404"](req,res);
		}

		
		//res.end();
	}
});

server.listen(8000);
router.js

var fs = require("fs");
var router = {
	"index":function(req,res){
		fs.readFile("./index.html",function(err,data){
			res.write(data);
			res.end();
		})
	},
	"about":function(req,res){
		fs.readFile("./about.html",function(err,data){
			res.write(data);
			res.end();
		})
	},
	"mine":function(req,res){
		fs.readFile("./mine.html",function(err,data){
			res.write(data);
			res.end();
		})
	},
	404:function(req,res){
		fs.readFile("./404.html",function(err,data){
			res.write(data);
			res.end();
		})
	}
};
module.exports = router;
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		我的页面1
	</body>
</html>



<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		我的页面2
	</body>
</html>




<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		我的页面3
	</body>
</html>




<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		我的页面4
	</body>
</html>

猜你喜欢

转载自blog.csdn.net/QQ_Empire/article/details/81484678
今日推荐