/*
* 实例说明:
* 1、创建一个服务器;
* 2、解析当前的url;
* 3、根据url并作出相应的响应
*/


var http=require("http");
//导入文件模块
var fs=require("fs");
var url=require("url");
var server =http.createServer(function(req,res){

//使用req.url获取当前url,注:url在使用时,需要用url.parse进行解析
var urlObj=url.parse(req.url);
var pathname=urlObj.pathname;

//在控制台输出当前的pathname
// console.log(pathname);

//判断pathname,进行相应路径的跳转
if(pathname=="/"){
goPage("/index.html",res);
}
else if(pathname=="/login.html"){
goPage(pathname,res);
}
else {
goPage(pathname,res);
}

//监听端口,注:一个程序只能监听一个端口
}).listen(8888);

//判断pathname,响应并返回相应页面
function goPage(pathname,res){
fs.readFile(pathname.substr(1),"utf-8",function(err,data) {
if(err){

//在控制台打印出错误信息
//console.log("Error:"+err);

// //修改header状态码,返回404页面
res.writeHeader("404");

//调用404页面(notFound.html)
fs.readFile('notFound.html', 'utf-8', function(err, data) {
res.end(data.toString());
});
}else{
//设置头信息
res.setHeader("Content-Type","text/html;charset='utf-8'");
//返回index.html页面
res.end(data);
}
});
}
posted on 2015-04-22 15:34  神经质女孩  阅读(272)  评论(0编辑  收藏  举报