2013-10-27 103 views
0

m trying to run simple http server and when something is typed in the Url to respond with the html file ,but it不是working.Here是代码HTTP服务器响应HTML文件

var http=require('http'); 
var fs=require('fs'); 
console.log("Starting"); 
var host="127.0.0.1"; 
var port=1337; 
var server=http.createServer(function(request,response){ 
    console.log("Recieved request:" + request.url); 
    fs.readFile("./htmla" + request.url,function(error,data){ 
     if(error){ 
      response.writeHead(404,{"Content-type":"text/plain"}); 
      response.end("Sorry the page was not found"); 
     }else{ 
      response.writeHead(202,{"Content-type":"text/html"}); 
      response.end(data); 

     } 
    }); 
    response.writeHead(200,{"Content-Type":"text/plain"}); 
    response.write("Hello World!"); 
    response.end(); 
}); 
server.listen(port,host,function(){ 
    console.log("Listening " + host + ":" + port); 
}); 

我的工作区是C:\ XAMPP \ htdocs中\设计和该HTML文件中的路径C:\ XAMPP \ htdocs中\设计\ htmla,我有一个HTML文件那里,我希望当它的网址打开打开.Noew它不显示我错误或HTML文件。只要显示地狱世界,无论我输入什么网址。

+0

也许您的路径存在问题?你可以通过你的程序输出(控制台消息)吗? – Atle

回答

1

这是因为读取的文件是异步的,所以文件在响应结束后在回调中输出。 最好的解决方案是只删除hello world行。

var http=require('http'); 
var fs=require('fs'); 
console.log("Starting"); 
var host="127.0.0.1"; 
var port=1337; 
var server=http.createServer(function(request,response){ 
    console.log("Recieved request:" + request.url); 
    fs.readFile("./htmla" + request.url,function(error,data){ 
     if(error){ 
      response.writeHead(404,{"Content-type":"text/plain"}); 
      response.end("Sorry the page was not found"); 
     }else{ 
      response.writeHead(202,{"Content-type":"text/html"}); 
      response.end(data); 

     } 
    }); 
}); 
server.listen(port,host,function(){ 
    console.log("Listening " + host + ":" + port); 
}); 
+0

是的,它的工作没有你好世界lines.Thank你 – dganchev