Getting Start with Express 4.x – Routes Basics – Tutorial 2

In this blog post we will see what are express routes and how to use them

Routes are basically used to decide which code should get execute when a particular URL gets opened.
So when we open/fetch different urls or different paths, based on the routes setup in express we can specify different logic to be executed.

If you come from a MVC background, routes is similar to controller. But since express doesn’t follow MVC this a very rough analogy.

You will find this code already in your “helloworld” application or the bare application generated using express-generator

var routes = require('./routes/index');
var users = require('./routes/users');
app.use('/', routes);
app.use('/users', users);

In this we are using two files routes/index.js, routes/users.js and telling express to use index.js for “/” and users.js for “/users” base urls

In index.js code goes like

router.get('/', function(req, res) {
  res.render('index', { title: 'Express' });

So what this does is quite simple, for a GET request on ‘’, we can write the code which should be executed.
Similarly, users.js will execute only for URLs which have ‘’ as the base path.

Similar other basic route types would be e.g in index.js we could add

//index.js'/', function(req, res) {
  var post_body = req.body;
  res.render('index', { title: 'POST Request' });
//this will respond to
router.get('/about', function(req, res) {
  res.render('index', { title: 'Express' });
//this will respond to
router.get('/list', function(req, res) {
  res.render('index', { title: 'User List' });

This is a tutorial on very basic routing in express, will see more advanced routing in further tutorials.

1. Create a new route for url
2. Create a new route for url