var http = require('http'),
fs=require('fs'),
path=require('path'),
host ='127.0.0.1',
port='9001';
var mimes = {
".htm":"text/html",
".css":"text/css",
".js":"text/javascript",
".gif":"text/gif",
".jpg":"text/jpeg",
".png":"text/png"
}
var server = http.createServer(function(req,res){
var filepath =(req.url==='/')?('./index.htm'):('.'+req.url);
var contentType = mimes[path.extname(filepath)];
//check file exists or not
fs.exists(filepath,function(file_exists){
if(file_exists)
{
res.writeHead(200, {'Content-Type' : contentType});
var streamFile = fs.createReadStream(filepath).pipe(res);
streamFile.on('error',function(){
res.writeHead(500);
res.end();
})
}
else
{
res.writeHead(404);
res.end("sorry we could not find the file you requested");
}
})
}).listen(port,host,function(){
console.log('server running on http://'+host+':'+port);
})
在上面的代码中,我的节点服务器给出了它在 127.0.0.1:9001 中运行的消息,但是当我在浏览器中运行它时,我遇到了“找不到错误 404 文件”,这不是我提到的错误。我也在这个脚本文件的同一个文件夹中有 index.html 文件。我的代码有什么问题?