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 ‘http://127.0.0.1:3000/’, we can write the code which should be executed.

Similarly, users.js will execute only for URLs which have ‘http://127.0.0.1:3000/users’ as the base path.

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

  
//index.js
  
router.post('/', function(req, res) {
    
var post_body = req.body;
    
console.log(post_body);
    
res.render('index', { title: 'POST Request' });
  
});
  
  
//index.js
  
//this will respond to http://127.0.0.1:3000/about
  
router.get('/about', function(req, res) {
    
res.render('index', { title: 'Express' });
  
});
  
  
//users.js
  
//this will respond to http://127.0.0.1:3000/list
  
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.


Experiment
1. Create a new route for url http://127.0.0.1:3000/users/account/createPassword
2. Create a new route for url http://127.0.0.1:3000/catalog/product/view

excellence-social-linkdin
excellence-social-facebook
excellence-social-instagram
excellence-social-skype