Express: Routing

app.METHOD(PATH, HANDLER)  

Where:

 

simple helloworld app (index.js or whatever you want to call it

 

//require the Express module and call express
var express = require('express')
var app = express()

//Following declares URI path / will cause the message Hello World to be sent
app.get('/', function (req, res) {
res.send('Hello World!')
})

 

//application will listen for requests on port number 300
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})

another example (index.js) that does more routing

var cool = require('cool-ascii-faces');
var express = require('express');
var app = express();
var pg = require('pg');
app.set('port', (process.env.PORT || 5000)); //setting  variable "port" to 5000
app.use(express.static(__dirname + '/public'));
// views is directory for all template files in project
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
//map URI / to index.ejs in teh sub-directory pages 
app.get('/', function(request, response) { response.render('pages/index'); });
//map URI /nodeMongoDBTest to nodeMongoDBTest.ejs in the sub-directory pages 
app.get('/nodeMongoDBTest', function(request, response) {
      response.render('pages/nodeMongoDBTest');
});
           
//when URI /cooll requested call the cool function from the cool module required at top
app.get('/cool', function(request, response) {
  response.send(cool());
});


//when URI /times requested call the inline function which increments #times run
app.get('/times', function(request, response) {
             var result = ''
             var times = process.env.TIMES || 5
             for (i=0; i < times; i++)
             result += i + ' ';
             response.send(result);
 });
//associated listening port to variable "port" which was set above to 5000
app.listen(app.get('port'), function() {
             console.log('Node app is running on port', app.get('port'));
});
           

          
 

Decomposing the app.get() call

What is this request object and response object

req object

  • req.params.name_of_param

The req object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on. In this documentation and by convention, the object is always referred to as req (and the HTTP response is res) but its actual name is determined by the parameters to the callback function in which you’re working.

For example:

app.get('/user/:id', function(req, res) {
    res.send('user ' + req.params.id);
  });  

But you could just as well have:

app.get('/user/:id', function(request, response) {
    response.send('user ' + request.params.id);
  });
  • req.baseUrl, req.body, req.cookies (req.cookies.name_of_cookie), req.hostname, req.path, etc see documentation

NOTE: if you want to see the body of the request for printing it out do the following

console.log(JSON.stringify(req.body));

 

if you do the following will brint out a "Object"

console.log(req.body);

 

For example the following handler code:

var body = JSON.stringify(req.body);
 var params = JSON.stringify(req.params);
 res.send("recieved your request!</br>" + "parameters: " + params +
"</br>URL:" + req.url + "body: " + body);

 

will produce

  • req.body

    Contains key-value pairs of data submitted in the request body.

res object

 

  • res.render, res.send, res.cookie, res.redirect, and many more

 

Respond to POST request on the root route (/), the application’s home page:

app.post('/', function (req, res) {
    res.send('Got a POST request')
  })  

Respond to a PUT request to the /user route:

app.put('/user', function (req, res) {
    res.send('Got a PUT request at /user')
  })  

Respond to a DELETE request to the /user route:

app.delete('/user', function (req, res) {
    res.send('Got a DELETE request at /user')
  })

In the following example, the handler will be executed for requests to “/secret” whether you are using GET, POST, PUT, DELETE, or any other HTTP request method that is supported in the http module.

app.all('/secret', function (req, res, next) {
    console.log('Accessing the secret section ...')
    next() // pass control to the next handler
  })

 

 

If you want multiple handlers for a Route -- notice the IMPORTANT use of next() --so goes to next handler function

var cb0 = function (req, res, next) {
    console.log('CB0')
    next()
  }

var cb1 = function (req, res, next) {
    console.log('CB1')
    next()
  }

var cb2 = function (req, res) {
    res.send('Hello from C!')
  }

// DEFINE MULTIPLE handler functions for the URI /example/c
app.get('/example/c', [cb0, cb1, cb2])

 

Routing Patterns

Here are some examples of route paths based on string patterns.

This route path will match acd and abcd.

app.get('/ab?cd', function (req, res) {
    res.send('ab?cd')
  })  

This route path will match abcd, abbcd, abbbcd, and so on.

app.get('/ab+cd', function (req, res) {
    res.send('ab+cd')
  })  

This route path will match abcd, abxcd, abRANDOMcd, ab123cd, and so on.

app.get('/ab*cd', function (req, res) {
    res.send('ab*cd')
  })  

This route path will match /abe and /abcde.

app.get('/ab(cd)?e', function (req, res) {
    res.send('ab(cd)?e')
  })  

Examples of route paths based on regular expressions:

This route path will match anything with an “a” in the route name.

app.get(/a/, function (req, res) {
    res.send('/a/')
  })  

This route path will match butterfly and dragonfly, but not butterflyman, dragonflyman, and so on.

app.get(/.*fly$/, function (req, res) {
    res.send('/.*fly$/')
  })

 

Routing Parameters

= named URL segments

The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys.

 

example 1

 

Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989

req.params: { "userId": "34", "bookId": "8989" }  

To define routes with route parameters, simply specify the route parameters in the path of the route as shown below.

app.get('/users/:userId/books/:bookId', function (req, res) {
    res.send(req.params)
  })

 

 

 

Response Methods

If none of these methods are called from a route handler, the client request will be left hanging.

Method Description
res.download() Prompt a file to be downloaded.
res.end() End the response process.
res.json() Send a JSON response.
res.jsonp() Send a JSON response with JSONP support.
res.redirect() Redirect a request.
res.render() Render a view template.
res.send() Send a response of various types.
res.sendFile() Send a file as an octet stream.
res.sendStatus() Set the response status code and send its string representation as the response body.

 

 

 

 

app.route()

You can create chainable route handlers for a route path by using app.route(). Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more information about routes, see: Router() documentation.

Here is an example of chained route handlers that are defined by using app.route().

app.route('/book')
    .get(function (req, res) {
      res.send('Get a random book')
    })
    .post(function (req, res) {
      res.send('Add a book')
    })
    .put(function (req, res) {
      res.send('Update the book')
    })  

express.Router

Use the express.Router class to create modular, mountable route handlers. A Router instance is a complete middleware and routing system; for this reason, it is often referred to as a “mini-app”.

The following example creates a router as a module, loads a middleware function in it, defines some routes, and mounts the router module on a path in the main app.

Create a router file named birds.js in the app directory, with the following content:

var express = require('express')
var router = express.Router()


 // middleware that is specific to this router
router.use(function timeLog (req, res, next) {
    console.log('Time: ', Date.now())
    next()
  })


 // define the home page route
  router.get('/', function (req, res) {
    res.send('Birds home page')
  })


 // define the about route
  router.get('/about', function (req, res) {
    res.send('About birds')
  })


  module.exports = router  

Then, load the router module in the app:

var birds = require('./birds')


 // ...

 app.use('/birds', birds)  

The app will now be able to handle requests to /birds and /birds/about, as well as call the timeLog middleware function that is specific to the route.

 

 

© Lynne Grewe