簡體   English   中英

NodeJS靜態文件夾中的HTML無法加載具有相對路徑的資產

[英]HTML in NodeJS static folder can't load assets with relative path

我為NodeJS網站使用一個靜態文件夾,但是奇怪的是,在index.html中,我仍然需要包含該文件的文件夾的路徑。

將文件夾名稱添加到路徑可以解決此問題,但只能在提供的初始index.html頁面中。 在隨后的任何頁面中(單擊站點中的超鏈接后),文件夾名稱突然都不是路徑的一部分!

dist
  └── viewer
   ├── index.html
   ├── test.html
   ├── style.css
   └── game.js

節點

app.use(express.static('dist'))
app.get('/viewer', function (req, res) {
    res.sendFile(__dirname + '/viewer/index.html')
})

INDEX.HTML

我無法使用./路徑加載資源,即使它們位於同一文件夾中

// WORKS
<link rel="stylesheet" href="./viewer/style.css">
// NOT WORKING
<script src="./game.js"></script>

測試HTML

如果單擊index.html中指向test.html的鏈接,則該行為突然相反!

// NOT WORKING
<link rel="stylesheet" href="./viewer/style.css">
// WORKS
<script src="./game.js"></script>

如何獲得指向節點站點中所有頁面上正常工作的資產的鏈接?

嘗試使用確切的路徑

<script src="/viewer/game.js"></script>

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

您可以檢查文件是否在瀏覽器中正常工作

像開

http://localhost/viewer/style.css

http://localhost/viewer/game.css



如果您不想使用確切的路徑,則必須設置正確的路徑,因為test.html位於viewer文件夾中

所以在test.html中,您需要添加

<script src="./game.js"></script>

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



在路由中,您正在瀏覽器http:// localhost / viewer中訪問index.html

那么正確的來源路徑如下

<link rel="stylesheet" href="./viewer/style.css">
<script src="./viewer/game.js"></script>

當路由將目錄更改為/

如果您以http://localhost/viewer/index.html訪問index.html ,則正確的路徑為

<link rel="stylesheet" href="./style.css">
<script src="./game.js"></script>


在您的情況下,您將使用以下命令混淆路由器:

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

有一個名為index.html的文件,當您輸入目錄時,大多數服務器會在該目錄中查找index.html 如果可用,它將僅顯示index.html文件。

如果靜態文件夾中存在目錄,則不應添加路由。



PS:最佳做法是使用源的確切路徑。



希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM