Understanding Routing in Node.JS with Express 4

Node makes application development hell lot easier and on top of the Express make it fun to quick spin up application. In this article we w...

Node makes application development hell lot easier and on top of the Express make it fun to quick spin up application. In this article we will be discussing routing mechanism in node.js using Express. I recommend reading express documentation on routing which are self-explanatory, but here is quick example routing in Node.js

Let begin by creating a user database, I have added sample json you can also generate sample json here 

[
  {
    "gender": "female",
    "name": {
      "title": "miss",
      "first": "mary",
      "last": "jones"
    },
    "email": "mary.jones56@example.com",
    "username": "crazypeacock512"
  },
  {
    "gender": "male",
    "name": {
      "title": "mr",
      "first": "alan",
      "last": "walters"
    },
    "email": "alan.walters29@example.com",
    "username": "crazytiger134"
  }
]

Nodemon - I used nodemon for this example, I recommend using nodemon for your node application to monitor your node changes, lets generate our package.json. In here I created index.js as landing page for our application

{
    "name": "NodeRouting",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "start": "node index.js",
        "dev": "nodemon index.js"
    },
    "keywords": [],
    "author": "Harshit Pandey",
    "license": "ISC",
    "dependencies": {
        "express": "^4.13.1",
        "lodash": "^3.10.0"
    },
    "devDependencies": {
        "nodemon": "^1.3.7"
    }
}

Lets read through the file (users.json) through fileStream read of node and parse through file for each name in the json object and store in users arrary 'users[]'

var users = []

fs.readFile('users.json', {encoding: 'utf8'}, function (err, data) {
  if (err) throw err

  JSON.parse(data).forEach(function (user) {
    user.name.full = _.startCase(user.name.first + ' ' + user.name.last)
    users.let bpush(user)
  })

})

Routing to default 

Routing starts here now, since have to code to loop through json and parse through file using file buffer, we can simply map a route now to generate simplified response

Lets begin by setting defaulted app route for '/'

app.get('/', function (req, res) {
  var buffer = ''

  users.forEach(function (user) {
    buffer += '' + user.name.full + '
'
  })
  res.send(buffer)
})


Routing with keyword 

Assuming user pass on ':username' in url context, we need give response with correct user matching username, this can be done simply by

app.get('/:username', function (req, res) {
  var username = req.params.username
  res.send(username)
})

Routing with Regular Expression

If you are not sure with keyword, want to offer weak match using regular expression. You can also simply pass on your expression like shown here

app.get(/big.*/, function (req, res, next) {
  console.log('BIG USER ACCESS')
  next()
})

Routing to Regular File

In expression 4.0, you can use sendFile() method now to redirect user to flat file like 'index.js' or 'index.html'

res.sendFile() is supported by Express v4.8.0 onwards.

app.get('/index', auth.protected, function(req, res) {
    res.sendFile('/index.html');
});

Routing with JSON response

You can revert back with JSON response simply by

res.status(500).jsonp({ error: 'message' });

Routing to a specific url 

Simply with redirect() method you can redirect to a url

res.redirect('/foo/bar');
res.redirect('http://example.com');
res.redirect(301, 'http://example.com');
res.redirect('../login');

Routing to download file (PDF/Word or more)

Simply replace by download() method


res.download('/report-12345.pdf');

res.download('/report-12345.pdf', 'report.pdf');

res.download('/report-12345.pdf', 'report.pdf', function(err){
  if (err) {
    // Handle error, but keep in mind the response may be partially-sent
    // so check res.headersSent
  } else {
    // decrement a download credit, etc.
  }
});

In the next post, we will continue towards building REST API with Node, followed by pulling data from Postgres.

Source Code

The source code for the application is available in this repository.
To install and run the app:
  1. Clone the noderouting repository:
    1
    git clone https://github.com/mailtoharshit/NodeRouting
  2. Navigate (cd) to the noderouting  directory.
  3. Install the dependencies:
    1
    npm install
  4. Start the application:
    1
    npm run dev

What Others Are Reading