第一版
var http = require('http')
http.createServer(function (req,res) { // 创建服务器
// 规范化url,去掉查询字符串
var path = req.url.replace(/\/?(?:\?.*)?$/,'').toLowerCase()
switch(path){
case '':
res.end('Home')
break;
case '/about':
res.end('ABout')
break;
}
}).listen(8866)
console.log('listening on 8866............')
第二版
var http = require('http')
var fs = require('fs')
function serveStaticFile(res,path,contentType,responseCode){
if(!responseCode) responseCode = 200
fs.readFile(__dirname + '/' + path,function(err,data){
console.log(err)
if(err){
res.writeHead(500,{'Content-Type':'text/plain'})
res.end('500-Interal Error')
}else{
res.writeHead(responseCode,{'Content-Type': contentType});
res.end(data)
}
})
}
http.createServer(function (req,res) {
var path = req.url.replace(/\/?(?:\?.*)?$/,'').toLowerCase()
switch(path){
case '':
serveStaticFile(res,'home.html','text/html')
break;
case '/about':
serveStaticFile(res,'about.html','text/html')
break;
case '/img/logo.png':
serveStaticFile(res,'img/logo.png','image/png')
break;
default:
serveStaticFile(res,'notfound.html','text/html',404)
}
}).listen(8866)
console.log('listening on 8866............')