0

I have the following folder structure:

/app
    server.js
/public
    1.jpg

I want to be able to access the 1.jpg image from the URI /1.jpg.
In my server.js file, I added the following middleware at the top:

app.use('/', express.static('../public'));

and in the buttom i have a middleware that catch not found routes:

app.all('*', (req, res) => {
    res.status(404).json({
        success: false,
        message: `Can't find ${req.originalUrl} on this server!`
    });
});

When i make a request to: /1.jpg i got the following response:

{
    "success": false,
    "message": "Can't find /1.jpg on this server!"
}

Even if it should serve the first middleware which is the image

Ayoub k
  • 7,788
  • 9
  • 34
  • 57
  • Not really related, but in production build, [it's better to serve static file using nginx / apache](https://stackoverflow.com/a/44796116/12397250) – Owl Jul 07 '20 at 19:07

1 Answers1

1

The issue might be caused by the relative path to the public directory because the path is relative to the directory from where you launch your app.

If this is the case, then providing the absolute path should fix it:

const path = require('path');
app.use('/', express.static(path.join(__dirname, '../public')))
antonku
  • 7,377
  • 2
  • 15
  • 21