How can I serve a default image file in express.js? - javascript

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?

At the bottom of the routes, make a default one:
app.get('/dist/img/fileicons/*', function(req, res) {
res.sendfile('path/to/blank.png')
});

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.

Related

How would I add URL subsections/subpages?

How would I add things like this:
/page/sub-section
ex: https://url.com/account/notifications
In terms of a static site, each slash represents a single directory on your web server.
/page/sub-section
Would mean you have the
/ the root directory
/page a folder called page
/sub-section another folder called sub-section
In the last folder, you would then have your index file, which will be loaded once visiting the URL. For example index.html.
In terms of web development this is named routing and all the big web frameworks come with own modules for routing. Here you don't have to create directories as described above, instead these frameworks will handle the request and route it internally to find the right content and display it for that route.

How to serve files from express 4.0 public folder as formatted html and not files, based on extension? E.g. format JSON, show images

Hey so anytime I place something in the "public" dir of my express directory, it automatically has a link on my webpage that I like. For example, going to https://website.com/image.jpg will allow me to download an image, and https://website.com/object.json will allow me to download a JSON file, without me having to do anything aside from place these files in my public folder. This is super convenient since I have another script that could be making a bunch of different things that I won't want to specify by name on my server every time I change something.
What I would like to do is modify this serve command so that when I want to retrieve an image, instead of automatically downloading it, it displays it in the browser. This should be as simple as adding an <html> </html> around anything in the public folder that has the .png file ending. Likewise, I would like to stringify any JSON file so that it comes out in a readable format (JSON.stringify(object,null,2));
Basically, I would like to be able to just put something in my public folder and automatically be able to access it in a desirable way based on its file extension. In these two cases the "desirable" way is not downloading the file, but displaying it in-browser in a human-friendly format.
display of static files in nodejs is not a trivial behavior. you'd usually set a folder as static which becomes public and end url fragment is same as file name. Using Express with Nodejs, it looks like this.
app.use(express.static(path.join('.', 'public')));
Because you don't like default implementation, you can rather parse the url manually, check if a file by that name exists, wrap it around appropriate html, and throw it as response.
var fs = require('fs');
app.use(function(req, res, next){
fileName = req.url.substring('https://website.com/'.length);
if(fs.existsSync('public/'+fileName){
if(fileName.substring(fileName.lastIndexOf('.')+1)=='jpg')
res.send('<html><body><img src="public/'+fileName+'"></img></body></html>')
})
As you can see, all urls are checked for files. You can also use a router while placing all public files under some subdirectory like '/public'

Serving directory images using Express Js

I have a simple use case for an application; a user can upload images to server where they are stored in a directory, and a user can view all images uploaded and stored in this directory.
The functionality for the first criteria is working, and the application persists uploaded images to the image directory.
The next step is to return all images. For the front end, i will use some kind of tile gallery to render images to the user. However, my question is related to how best to return "all images" to the end user, through express js.
Essentially, I am hoping to do a directory dump, but am confused as to an elegant (read: any!) solution on how to do this. Any advice or suggestion most appreciated.
Edit: to clarify, the route should return all images when hit. As future implementations will filter images based on certain criteria.
example:
// return the view page for register
app.get('/gallery',function(req,res){
// return images here
res.send();
});
If I understood you correctly, all you need to do is to statically serve a folder. For that, you can use
app.use('/images', express.static('path/to/images'))

Match all routes with or without .html extension, except for static assets

I'm trying to set up a generic handler for every request that is not something like an image or favicon or anything like that. For example I want this handler to handle /index, /index.html, /user/123, etc., but not /favicon.ico, /sunflower.png, /images/starfish.png, etc.
This is currently what I have
app.get('/:name', (req, res) => {
res.render(req.params.name)
})
But this is of course matching /favicon.ico, and every other url that I don't want it to match. It also doesn't match .html extensions. Is there a clean solution out there for this situation?
The best solution in a production environment to serve static assets, like the images you have listed, is to place a front facing proxy (eg: nginx) in front of Express and configure it accordingly.
That way, request for static assets are offloaded to the proxy, and never reach Express. Express is best for serving dynamic content asynchronously, do not use it for serving files.

Paths in nodejs

I'm facing a problem with paths in nodeJs, I route the user to the index page when he specifies the language in the url like this :
app.all('/:locale?/index',function(req,res,next){
if(!req.params.locale){
console.log('no param');
res.render('index');
} else {
var language = req.params.locale;
i18n.setLocale(language);
res.render('index');
}
});
However, in my index.html page the source of images are specified this way : ./images/img1.png , when I route the user, my index.html shows image not found because it considers the path " lang/images/img1.png , it considers the languge in my URL, could you please help?
Thank you
The . in your path is telling the app to look at the current folder, which is lang. You should be able to get around this by specifying either a URL:
<img src="http://myApp.com/images/img1.png">
or by specifying the path from the root directory (everything except http://myApp.com)
<img src="/images/img1.png">
This is probably a better solution, since you can swap your domain easily; for example, working on your local machine (http://localhost:3000/) vs. a deployed app (http://myApp.com)
Generally speaking, I'd almost always use the path from root rather than a relative path (e.g., ./...), since I may move pages around in refactoring, and it's easier to look for direct references than relative ones if I have to change anything.

Categories