1

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);
2
  • Please show how you reference the files in management.html Commented Jun 3, 2017 at 14:33
  • 1
    Use absolute paths (starting with a /), not relative, in your HTML code. Commented Jun 3, 2017 at 14:34

1 Answer 1

2

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">.

Sign up to request clarification or add additional context in comments.

2 Comments

How come the absolute path starts inside my public folder and not my app folder?
@TimurOzkul That's due to the express.static(path.join(__dirname, 'public')). This basically says that the public folder is the root of your static files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.