2016-09-07 32 views
0

我在nodeJS做了一個小程序,cloud9應該啓動我的html。它的工作,但沒有CSS。我嘗試了很多東西,但沒有找到解決方案。Nodejs加載我的HTML沒有CSS

var http = require("http"); 
var fs = require("fs"); 
var events = require('events'); 
var eventEmitter = new events.EventEmitter(); 

fs.readFile('homepage.html', function(err, data) { 
    if (err) return console.log(err); 

    var server = http.createServer(function (request, response) { 
    response.writeHead(200, {'Content-Type': 'text/html'}); 
    response.writeHead(200, {'Content-Type': 'text/css'}); 
    response.write(data); 
    response.end(); 
    }).listen(8081); 
}); 

console.log("Server running."); 

我的HTML:

<!DOCTYPE html> 
<html> 
<head> 
    <title>My project</title> 
    <meta charset="UTF-8"> 
    <link rel="stylesheet" href="css/style.css"/> 
</head> 
<body> 
    <h1>My project</h1> 
    <p>coming soon</p> 
</body> 

`

我的CSS:

h1{ 
    font-size: 4px; 
} 

我想通過我的瀏覽器,我的H1只打開的.html爲4像素。

+0

能否列出html文件 –

+0

CSS文件是否可以通過HTTP訪問? – Leo

+0

我編輯我的文章添加HTML。 我不知道利奧,我該如何檢查? – Tellimi

回答

0
<link rel="stylesheet" href="css/style.css"/> 

你告訴瀏覽器加載css/style.css

瀏覽器詢問服務器。

response.writeHead(200, {'Content-Type': 'text/html'}); 

服務器說: 「這是一些HTML!」

response.writeHead(200, {'Content-Type': 'text/css'}); 

然後它說: 「下面是一些CSS!」

這很奇怪。您可以發送HTML文檔獨立樣式表。你不能同時發送兩個。

response.write(data); 

然後向服務器發送的homepage.html

內容因此,當瀏覽器向樣式表,它得到的網頁的另一個副本。

您需要注意the request object,它告訴你瀏覽器正在請求什麼。特別要注意methodurl屬性。

然後你需要給它一個特定的URL正確的響應(其中應包括正確內容類型的文件類型,並可能是一個404錯誤,如果它是不適合的東西你的請求期待)。

目前你總是發送主頁。如果瀏覽器要求/,則發送主頁。如果它要求/css/style.css,則發送主頁。如果它要求/this/does/not/exist,則發送主頁。

+0

我會閱讀並根據你的答案進行一些研究,以獲得解決方案。 感謝您的幫助,我瞭解了一點模式瀏覽器和服務器如何交互 – Tellimi