创建一个服务器,解析当前的url并根据url并作出相应的响应

/*
* 实例说明:
* 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);
}
});
}

转载于:https://www.cnblogs.com/shenyulin/p/4447645.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值