0xtimur
0xtimur

Reputation: 1293

express.static only loading to index.html

I am trying to get the static files (images, js, css) which are all inside the public folder to be available to all my routes. I am able to ONLY load them to the index.html. The management.html files does not have access to the static files, I am getting 404 error on the Chrome console.

Folder Structure:

-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);

Upvotes: 1

Views: 1523

Answers (1)

Duncan Lukkenaer
Duncan Lukkenaer

Reputation: 14004

Inside your HTML files you are probably referring to the relative paths of the static files. For example: <img src="img/example.png">. This link will be based on your current location.

When your current location is http://example.com/ (index.html), then it will refer to http://example.com/img/example.png, where the file is probably located.

But when your location is http://example.com/management (management.html), it refers to http://example.com/management/img/example.png, which will return a 404.

Using the absolute path of this file will solve this problem. You can do this by putting a / in front of the relative path: <img src="/img/example.png">. Alternatively you could use a relative path in management.html like this: <img src="../img/example.png">.

Upvotes: 2

Related Questions