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

1

1 Answer 1

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')))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.