I'm testing express and I ran across a problem that I haven't found a good solution for. My relative paths inside of index.htm are getting confused by a route.
Inside of server.js I include the following basic route.
server.js
app.get('/', function(request, response) {
response.sendFile(path.join(__dirname, 'public/index.htm'));
});
The folder /public
contains my index.htm file.
The folder /public/images
contains a single .png file used for testing.
Inside of index.htm I include the following line of code.
index.htm
<img src="images/testImage.png">
On a standard website this simple directory structure works fine. When index.htm is rendered it looks one directory up to /images to find testImage.png. However when I call it with an express route it gets confused and can't find the image.
In my browser when I visit http://localhost:3000/
the route correctly finds index.htm inside of the public folder. Unfortunately it renders the image link as broken and it gives me this error.
GET http://localhost:3000/images/testImage.png 404 (Not Found)
I can fix the problem by including this line of code in server.js. It tells express that calls to /images should actually go to public/images.
app.use('/images', express.static(path.join(__dirname, 'public/images')));
But going forward that line makes things more confusing and could lead to other problems.
Is there a standard practice to solve this kind of problem? Thanks so much!