2013-10-27 142 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