0

m trying to run simple http server and when something is typed in the Url to respond with the html file ,but it不工作。这是代码

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\designs 并且 html 文件位于路径 C:\xampp\htdocs\designs\htmla 中,我在那里有一个 html 文件,我想要在输入 url 时打开.Noew 它没有向我显示错误或 html 文件。无论我在 url 中输入什么,都只是显示地狱世界。

4

1 回答 1

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); 
});
于 2013-10-27T11:17:20.163 回答