0

I have trouble getting files from the correct folders when using a nested route in Node JS.

In a standard route like:

router.get('/something', (req, res) => {
  res.render('something.html')
})

This <img src="img/image-123.jpg"> inside something.html works.

However, it doesn't work in createProduct.html using this route:

router.get('/admin/createProduct', (req, res) => {
  res.render('createProduct.html')
})

because the browser tries to look for admin/img/image-123.jpg which doesn't exist.

I have both routes in an index.js file using app.use(require('./routes/index'))

And these are the static folders:

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

This is my file structure:

enter image description here

How can I prevent this behavior?

DonSeverino
  • 121
  • 10
  • 1
    Don't use path relative URLs for your images in your HTML. Instead, start the image URLs in the HTML with `/` so they are not relative to the path of the page and can easily be handled by a simple `express.static()` in your server. – jfriend00 Jan 19 '21 at 03:22

1 Answers1

0

Add this line to access static files in subroutes in /admin:

app.use('/admin', express.static(path.join(__dirname, 'public')))
Marc Selman
  • 752
  • 1
  • 8
  • 14