2014-08-29 18 views
2

在本地機器上,我想在Node上部署靜態網頁(包含HTML,CSS,JS文件),而不使用任何框架(例如Express)。我沒有把相關的文件到公用文件夾的網頁,然後調用的index.html,通過使用節點FS庫,如下所示:Node.JS上的靜態Web部署(不使用任何框架)

var http = require('http'), fs = require('fs'); 

fs.readFile('./public/index.html', function (err, html) { 
    if (err) { throw err;} 
    http.createServer(function(request, response) { 
    response.writeHeader(200, {"Content-Type": "text/html"}); 
    response.write(html); response.end(); 
    }).listen(1337, '127.0.0.1');; 
}); 

我用捲曲的所有文件(HTML, CSS,JS)實際上部署在本地主機上。但是,當我轉到localhost上的端口1337時,它會顯示HTML內容,但不會顯示以index.html導入的JS編寫的行爲。

+0

您的服務器設置在端口1337上,而不是80.您訪問了正確的端口嗎? – Sirko 2014-08-29 13:34:02

+0

轉到http://127.0.0.1:1337 – 2014-08-29 13:34:19

+0

@Sirko對不起,做了端口號錯誤,但我仍然沒有得到的行爲(寫在公共目錄中的JS文件)。 – 2014-08-29 13:48:29

回答

3

您的index.html文件正在向index.js(或任何JS文件所在的文件)發出單獨請求。您的服務器將以相同方式每處理:服務index.html文件的內容。

以這種方式創建服務器不會像其他服務器(如Apache可能)那樣自動爲文件系統提供文件。相反,你需要做的是這樣的:

http.createServer(function(request, response) { 
    if (request.url == "/index.html" || request.url == "/") { 
    response.writeHeader(200, {"Content-Type": "text/html"}); 
    fs.createReadStream("./public/index.html").pipe(response); 
    } 
    else if (request.url == "/index.js") { 
    response.writeHeader(200, {"Content-Type": "text/javascript"}); 
    fs.createReadStream("./public/index.js").pipe(response); 
    } 
}).listen(1337, '127.0.0.1'); 

當然寫的要提供服務的文件系統中的每個文件的路線可能是非常愚蠢的。你可以使用static file server module,或者自己實現一個靜態文件服務器。這將涉及根據請求URL檢查文件系統,然後使用正確的內容類型提供文件,您可以查看using a module like mime