2017-06-03 37 views
0

我想獲得靜態文件(圖像,js,css),這些文件都在公共文件夾內,可用於我的所有路線。我只能將它們加載到index.html。 management.html文件無法訪問靜態文件,我在Chrome控制檯上收到了404錯誤。express.static只加載到index.html

文件夾結構:

-app/ 
---index.html 
---management.html 
---public/ 
------css/ 
------js/ 
------img/ 

server.js:

const express = require('express'); 
const path = require('path'); 

var app = express(); 

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

app.get('/', function(req, res) { 
    res.sendFile('index.html', {root: __dirname }) 
}); 

app.get('/management', function(req, res) { 
    res.sendFile('management.html', {root: __dirname }) 
}); 

app.listen(3000); 
+0

請顯示如何引用'management.html'中的文件 –

+1

在您的HTML代碼中使用絕對路徑(以'/'開頭,而不是相對)。 – robertklep

回答

1

裏面的HTML文件你可能指的是靜態文件的相對路徑。例如:<img src="img/example.png">。此鏈接將基於您當前的位置。

當你的當前位置是http://example.com/(index.html),那麼它將引用http://example.com/img/example.png,該文件可能位於。

但是當你的位置是http://example.com/management(management.html),它是指http://example.com/management/img/example.png,它會返回一個404

使用此文件的絕對路徑,那麼解決這個問題。您可以通過在相對路徑<img src="/img/example.png">前放置/來完成此操作。或者,您可以使用management.html中的相對路徑,如下所示:<img src="../img/example.png">

+0

絕對路徑如何在我的公共文件夾內而不是我的應用程序文件夾中啓動? –

+1

@TimurOzkul這是由於'express.static(path.join(__ dirname,'public'))''。這基本上說''公共'文件夾是你的靜態文件的根。 –