2014-07-20 118 views
1

我一直在關注nodejs的介紹this tutorial,但我很難用response.write()返回一些東西。Response.write()不返回值

當我轉到domain:8001,但導航到domain:8001/socket.html返回一個空白屏幕時,我的server.js代碼正常返回「hello world」。

我已經使用console.log來檢查編寫「socket在這裏」的代碼。正在執行,但我不知道爲什麼它沒有做任何事情。

server.js:

var http = require("http"); 
var url = require('url'); 
var fs = require('fs'); 

var server = http.createServer(function(request, response){ 
    console.log('Connection'); 
    var path = url.parse(request.url).pathname; 
      console.log(__dirname); 
      console.log(path); 

    switch(path){ 
     case '/': 
      response.writeHead(200, {'Content-Type': 'text/html'}); 
      response.write('hello world'); 
      break; 
     case '/socket.html': 
      fs.readFile(__dirname + path, function(error, data){ 
       if (error){ 
        response.writeHead(404); 
        response.write("opps this doesn't exist - 404"); 
       } 
       else{ 
        response.writeHead(200, {"Content-Type": "text/html"}); 

        response.write("socket is here."); 
       } 
      }); 
      break; 
     default: 
      response.writeHead(404); 
      response.write("opps this doesn't exist - 404"); 
      break; 
    } 

    response.end(); 
}); 

server.listen(8001); 

var io = require('socket.io').listen(server); 

socket.html:(儘管它不應該的問題中包含什麼吧)

<html> 
    <head> 
    <script src="/socket.io/socket.io.js"></script> 
    </head> 
<body> 
    <script> 
     var socket = io.connect(); 
    </script> 
    <div>This is our socket.html file</div> 
</body> 
</html> 
+0

您是否嘗試過不嘗試加載腳本的頁面?當腳本加載時,瀏覽器停止解析頁面,如果有問題可以解釋空白頁面。 – Guffa

+0

我試過沒有腳本的socket.html,但它似乎給我同樣的問題。 – Rho

回答

1

你在等待fs.readFile()之前結束的響應完成。試試這個:

var http = require("http"); 
var url = require('url'); 
var fs = require('fs'); 

var server = http.createServer(function(request, response){ 
    console.log('Connection'); 
    var path = url.parse(request.url).pathname; 
      console.log(__dirname); 
      console.log(path); 

    switch(path){ 
     case '/': 
      response.writeHead(200, {'Content-Type': 'text/html'}); 
      response.write('hello world'); 
      break; 
     case '/socket.html': 
      fs.readFile(__dirname + path, function(error, data){ 
       if (error){ 
        response.writeHead(404); 
        response.write("opps this doesn't exist - 404"); 
       } 
       else{ 
        response.writeHead(200, {"Content-Type": "text/html"}); 

        response.write("socket is here."); 
       } 
       response.end(); 
      }); 
      return; 
     default: 
      response.writeHead(404); 
      response.write("opps this doesn't exist - 404"); 
      break; 
    } 

    response.end(); 
}); 

server.listen(8001); 

var io = require('socket.io').listen(server); 

而且,這樣做fs.readFile(__dirname + path, ...);是潛在的危險,因爲有人可能會發送一個請求像/../../../../../../etc/passwd。您應該使用path模塊將__dirname + path解析/歸一化爲絕對路徑,然後確保該絕對路徑以公用目錄的絕對路徑開始。

+0

非常感謝。它現在效果很好。 – Rho