2015-03-08 64 views
0

爲什麼我的css文件只能看似隨機加載?我該如何解決這個問題?出於某些原因,我沒有使用Express來使用Nodejs。隨機地,我的css不會加載我的應用程序

var http = require('http'); 
var fs = require('fs'); 
http.createServer(function (request, response) { 
console.log('request starting...'); 

    fs.readFile('./view.html', function(error, content) { 
     if(error) { 
      response.writeHead(404); 
      response.end(); 
     } else { 
      response.writeHead(200, {'Content-Type': 'text/html'}); 
      response.end(content, 'utf-8'); 
     } 
    }); 

    fs.readFile('./css/appStylesheet.css', function(error, content) { 
     if(error) { 
      response.writeHead(404); 
      response.end(); 
     } else { 
      response.writeHead(200, {'Content-Type': 'text/css'}); 
      response.end(content, 'utf-8'); 
     } 
    }); 

}).listen(3000); 
console.log('Server running at localhost on port 3000'); 

以防萬一,這部分不是問題的所在,下面的代碼顯示HTML文件:

<!DOCTYPE html> 
<html> 
    <head> 
     <title>Sign In</title> 
     <link rel="stylesheet" type = "text/css" href="/css/appStylesheet.css"> 
    </head> 
    <body> 
     <p id = "signIn"> 
      <p>Username</p> 
       <input type = "text" id = "username" value = "" > 
        <script> 
        function username() { 
         var x = document.createElementById("username").value; 
         document.getElementById("demo").innerHTML = x; 
        } 
       </script> 
     <p>Password</p> 
      <input type = "text" id = "password" value = ""> 
      <p><button onclick = "password()">Submit</button></p> 
       <script> 
        function password() { 
         var x = document.createElementById("password").value; 
         document.getElementById("demo").innerHTML = x; 
        } 
       </script> 
    </p> 
</body> 
</html> 

回答

1

總之,異步是這裏的關鍵。

在您的代碼中,只有一個請求處理器,爲兩個不同的文件調用fs.readFile兩次。每個調用都有更多或更少的類似回調來處理內容。問題是,每個那些回調的結束這一行的響應:

response.end(content, 'utf-8'); 

現在你有一個經典的比賽條件 - 如果第二readFile贏得比賽(即,它完成閱讀第一進程),CSS文件送達。如果不是,則提供HTML文件。請注意,無論服務器實際查詢哪個文件都無關緊要,因爲您的回調根本不檢查請求!

您(最可能)必須做的事情是設置請求偵聽器,以便它檢查客戶端實際請求的內容 - 並僅提供此文件。一個可能的(並且非常簡單的)做法:

function serveFile(filePath, fileType, response) { 
    fs.readFile(filePath, function(err, content) { 
    if (err) { 
     response.writeHead(500); 
     response.end(); 
    } 
    else { 
     response.writeHead(200, { 'Content-Type': fileType }); 
     response.end(content, 'utf-8'); 
    } 
    }); 
} 

var contentTypeFor = { 
    '/view.html': 'text/html', 
    '/css/appStylesheet.css': 'text/css' 
}; 

http.createServer(function (request, response) { 
    if (request.url in contentTypeFor) { 
    serveFile(request.url, contentTypeFor[request.url], response); 
    } 
    else { 
    response.writeHead(404); 
    response.end(); 
    } 
}).listen(3000); 

入住這(與http://localhost:3000/view.html),你可以看到這兩個請求送達正確。

相關問題