2013-05-11 27 views
1

我正在使用Node.js,我想爲所有網址提供/index.html。Node.js:如何爲所有網址提供/index.html?

例如,我想成爲/index.html所有這些:

foo.com 
foo.com/index.html 
foo.com/bling 
foo.com/blah/index.html 

如果可能的話我寧願不改變瀏覽器顯示的URL。

這是可能的,如果是這樣,最好的辦法是什麼?

回答

2

可以使用,例如,express.js MVC NPM模塊

var express = require('express'); 
var app = express(); 

app.all('*', function(req, res){ 
    res.sendfile("index.html"); 
}); 

app.listen(3000); 
+2

看到你的答案太晚了,貼差不多了自己:)'res.sendfile(「的index.html」)'是充當最簡單的方法'index.html'。 – robertklep 2013-05-11 18:10:41

+0

@robertklep謝謝你,我已更正 – zavg 2013-05-11 18:12:33

+0

感謝你們倆。我現在意識到一個明顯的複雜因素......我想爲/index.html中包含的文件提供服務:CSS,JavaScript和圖像。我如何排除這些路徑,即/ css,/ js,/ images等下的所有路徑? – 2013-05-11 18:23:49

0

沒有明確,如果這是你的服務器需要做的唯一任務,您可以使用fs模塊在http服務器實例主要回調,管道中的readStream的迴應是這樣的:

http.createServer(function(request, response) { 
    fs.createReadStream('index.html', { 
     'bufferSize': 4*1024 
    }).pipe(response); 
}); 
相關問題