var http = require('http');
var url = require('url');
var fs = require('fs');
var server = http.createServer();
//返回当前文件的路径
var HtmlDir = __dirname + '/html/';
server.on('request',function(req,res){
var urlStr = url.parse(req.url);
switch (urlStr.pathname)
{
case '/':
//首页
sendData(HtmlDir+"index.html",req,res);
break;
case '/user':
sendData(HtmlDir+"user.html",req,res);
break;
default :
sendData(HtmlDir+"err.html",req,res);
break;
}
});
function sendData(file,req,res)
{
fs.readFile(file,function(err,data){
if(err){
res.writeHead(404,{
'content-type':'text/html;charset=utf-8'
});
console.log(data);
res.end('<h1>页面被吃带哦了</h1>');
}else{
res.writeHead(200,{
'content-type':'text/html;charset=utf-8'
});
res.end(data);
}
});
}
server.listen('8081','localhost');
07E13F24-C746-4C18-9B21-D33A6DD145D9.png