2017-02-28 25 views
0

我是Node.js中的新手;如果我的問題是不好意思啞:Node.js:如何路由網站地圖

我想從服務器返回index.html

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

app.get('/', function (req, res) { 
    res.sendFile(path.join(__dirname + '/index.html')); 
}); 

app.get('/elements/hello-world.html', function (req, res) { 
    res.sendFile(path.join(__dirname + '/elements/hello-world.html')); 
}); 

app.listen(1337); 

但也有在存儲與本地服務器上的相應結構html文件的許多資產。例如,對於返回/elements/hello-world.html,在本身位於根目錄下的元素文件夾下返回hello-world.html就足夠了。

但是在index.html中爲每個資產(如css es,image s等)編寫路徑是不合理的。 解決方案是什麼?

回答

2

看起來像你想要提供靜態文件,以提供靜態文件,如圖像,CSS文件和JavaScript文件,請使用Express中的express.static內置中間件功能。現在

app.use(express.static('public')) 

,你可以加載在公共目錄下的文件:

http://localhost:3000/images/kitten.jpg 
http://localhost:3000/css/style.css 
http://localhost:3000/js/app.js 
http://localhost:3000/images/bg.png 
http://localhost:3000/hello.html 

從官方文檔明確here

+0

謝謝,但什麼是公共目錄? – Hans

+0

是你想要服務的文件,在你的情況下,可能是「元素」文件夾 –

+0

我添加了'app.use(express.static('elements'));'並刪除了路線。現在找不到它。我錯過了什麼嗎? – Hans

1

的解決方案是app.use,像(CoffeeScript的):

app.use express.static(public_dir) 
app.use '/js', express.static(path.join(public_dir, '/js')) 
app.use '/css', express.static(path.join(public_dir, '/css')) 
app.use '/images', express.static(path.join(public_dir, '/images')) 
app.use '/fonts', express.static(path.join(public_dir, '/fonts')) 
app.use '/svgs', express.static(path.join(public_dir, '/svgs')) 

在拉我們的資源,如

<script type="text/javascript" src="/js/primus.js"></script> 
    <script type="text/javascript" src="/js/app_090.js"></script> 

中的index.html實際上,我不知道這回答你的問題,但這是如何在Express中完成資源類型路由。

1

您需要使用快速靜態模塊服用。

app.use(express.static(path.join(__dirname, 'public'))); 

在您的nodejs根文件夾中創建一個名爲public的文件夾,將您的index.html和您的元素文件夾放入其中。

現在,當您加載http://localhost/index.htmlhttp://localhost/elements/hello-world.html時,它應該沒有任何問題。