node 同步 跳转 登陆/首页 demo

demo2.js

var http = require("http");
var url = require("url");
/*	require同级目录的时候需要需要加上./
 * 否则会找不到文件
 */
var User = require("./User");

var myApp = http.createServer(function(request,response){
		/*防止两次访问服务器*/
	if(request.url != "/favicon.ico"){
		console.log("开始访问服务器");
		response.writeHead(200,{"Content-Type" : "text/html;charset = utf-8"});
		/*	截取浏览器url传递的参数	*/
		var pathname = url.parse(request.url,true).pathname;
		pathname = pathname.replace(/\//,"");
		
/*	第一种,以对象的形式访问	*/
//		User.login();
/*	第二种,以数组的形式访问	*/
//		User["login"]();

		User[pathname](response);		
	}
	response.end("关闭服务器");
});

myApp.listen(8000);
console.info("服务器启动成功");

User.js

var fs = require("fs");
/*	同步请求	*/
module.exports = {
	"login":function(response){
		var data = fs.readFileSync("login.html","utf-8");
		response.write(data);
	},
	"index":function(response){
		var data = fs.readFileSync("index.html","utf-8");
		response.write(data);
	}
}

index.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<div>首页</div>
	</body>
</html>


login.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<div>登陆</div>
	</body>
</html>



猜你喜欢

转载自blog.csdn.net/guohao326/article/details/78270894