简体   繁体   中英

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

I use a static folder for a NodeJS website, but strangely, in the index.html I still need to include a path to the folder that contains the files.

Adding the folder name to the path solves the problem, but only in the initial index.html page that is served. In any following pages (after clicking a hyperlink in the site), suddenly the folder name can NOT be part of the path!

FOLDER

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

NODE

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

INDEX.HTML

I can't load assets with ./ path, even though they're in the same folder

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

TEST.HTML

If you click a link in index.html which leads to test.html , the behaviour is suddenly reversed!

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

How can I get links to assets working normally across all pages in a node site?

try using the exact path

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

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

You can check if your file is working in the browser

like opening

http://localhost/viewer/style.css

http://localhost/viewer/game.css



If you don't want to use the exact path then you have to set the correct path, as test.html is inside viewer folder

so in test.html you need to add

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

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



In routing, you are accessing index.html in browser http://localhost/viewer

then the correct path of the sources would be as follows

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

as the route changes the directory to / .

if you are accessing index.html as http://localhost/viewer/index.html the correct path would be

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


In your case, you are confusing the router by using :

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

There is a file called index.html , when you enter a directory most server looks for index.html inside that directory. If available it just shows the index.html file.

You should not add route if a directory exists in a static folder.



PS: It is best practice to use the exact path of the source.



Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM