a blog for those who code

Wednesday, 2 March 2016

Routing Static files without file extension in Node.js

In this post we will discuss about routing in Node.js with or without file extensions. Routing is a mechanism to handle the request coming from client, processing the request and sending the response back to client. So sometimes there might be scenario where you want to process the request without depending on the file extension of the routes.

Routing helps the application to decide how to respond to a client request to a particular endpoint. Now lets say we want to add a route which will match all three endpoints i.e with about.html, about or about.htm. For only single endpoint (i.e. about) we write blow code

app.get('/about', function(req, res) {
  res.send('Hello World Express');
});

Also Read : Basic Routing in Node.js

Now if I ask you to write route for all three endpoints, you might write like below.

app.get('/about', function(req, res) {
  res.send('Hello World Express');
});
app.get('/about.html', function(req, res) {
  res.send('Hello World Express');
});
app.get('/about.htm', function(req, res) {
  res.send('Hello World Express');
});

The above approach is perfectly fine and it will server the purpose. I am not saying that you cannot write like above but just think instead of three options we have around 20 options to deal with. In that case using above approach we have to write app.get 20 times, that's not smart programming. Then how to deal with this scenario.

One thing to note that Express uses path-to-regexp for routing strings which means you can use regular expressions or string patterns to match routes.


So we can rewrite our code and it will be something like which reduces our code size.

app.get('/about|about.html|about.htm', function(req, res) {
  res.send('Hello World Express');
});

Other approach of doing the same thing would be :

app.get('/about(.html|.htm)?/', function(req, res) {
  res.send('Hello World Express');
});

 The above code will give us the output as


Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment

Contact Us

Name

Email *

Message *

Sponsers

Best Hosting Plans

CC License