1

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!

DR01D
  • 1,325
  • 15
  • 32
  • Possible duplicate of [static files with express.js](https://stackoverflow.com/questions/10434001/static-files-with-express-js) (you should mount your entire `public` folder as static, rather than specifically linking the images folder) – Joe Clay Jan 08 '18 at 16:07
  • 1
    `app.use(express.static('public'))` to serve static files from the public folder. https://expressjs.com/en/starter/static-files.html – Alex Polkhovsky Jan 08 '18 at 16:09
  • Bear in mind that relative links in HTML are resolved based on the URL, not the location on disk. If your server doesn't actually serve the `images` folder anywhere, your users won't be able to access it. – Joe Clay Jan 08 '18 at 16:10

0 Answers0