In my express.js project, I am serving up the dist folder of my project like so:
server.use(express.static('dist'))
In my dist folder, I have an img/fileicons folder that contains PNG files that represent various file types, e.g. 'txt.png', 'html.png', 'pdf.png', etc. In case an image doesn't exist for a given file type, I want to set up a default route that would serve up 'blank.png' with a generic file image. For example, if the URL '/img/fileicons/[doesn't exist].png' is hit, then 'blank.png' is returned. However, if I navigate to another path that doesn't exist, like '/html/[doesn't exist].html', then I don't want the 'blank.png' file served up.
How can I set up my express.js routing to accommodate this need?
All you need to do is put some middleware at the bottom of your stack and use res.sendfile()
. Don't forget to use res.statusCode(404)
so that crawlers don't think they're hitting a real resource.
At the bottom of the routes, make a default one:
app.get('/dist/img/fileicons/*', function(req, res) {
res.sendfile('path/to/blank.png')
});