Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express static serving wrong path

I am messing around with express.js and have built some basic functionality but am having issues with express static serving from the wrong place if the URL is longer than one directory from root. See the examples below.

I am using the normal documented approach to using static.

app.use(express.static(__dirname + '/public'));

And have set up a couple of routes. eg.

app.get('/signup', function(req, res) {
    res.render('signup.ejs');
});

With a 404 catch at the end of the chain.

app.get('*', function(req, res){
    res.status(404).render('404');
});

If I hit page such as localhost:3000 or localhost:3000/login which are defined routes, all is well. Even if I hit an undefined route of localhost:3000/foo, I get the 404 rendered correctly with all images present.

However if I go one further and do something like localhost:3000/login/foo all the images are missing and I will get an error in the browsers console with the following address.

http://localhost:3000/login/img/site-brand.png

This happens the same on routes defined with more than one directory too.

I interpreted the docs on the express website that regardless of what was calling for the static image it would be served from the public directory in root, which contains a js, img, and css directories.

My questions are, what have I misinterpreted? and how do I get express to always serve relative to root?

like image 688
Glenn Holland Avatar asked Dec 24 '22 14:12

Glenn Holland


1 Answers

I wrote the whole question then realised that when I had set up the src="" tags in my .ejs files I had used relative paths, not absolute. Rather than delete the question I decided to answer it and post it for others.

So instead of using src="img/my-image.png" it should be src="/img/my-image.png" The leading slash indicates that the request is relative to root not the path that is making the request.

Basic web development stuff there. I should have seen it first time out but its late, and I am cramming my head full of new frameworks which is in turn squeezing the more trivial stuff out of my small brain.

like image 119
Glenn Holland Avatar answered Jan 16 '23 01:01

Glenn Holland