Book Image

Node.js Blueprints

By : Krasimir Stefanov Tsonev
Book Image

Node.js Blueprints

By: Krasimir Stefanov Tsonev

Overview of this book

Table of Contents (19 chapters)
Node.js Blueprints
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Managing routes


The input of our application is the routes. The user visits our page at a specific URL and we have to map this URL to a specific logic. In the context of Express, this can be done easily, as follows:

var controller = function(req, res, next) {
  res.send("response");
}
app.get('/example/url', controller);

We even have control over the HTTP's method, that is, we are able to catch POST, PUT, or DELETE requests. This is very handy if we want to retain the address path but apply a different logic. For example, see the following code:

var getUsers = function(req, res, next) {
  // ...
}
var createUser = function(req, res, next) {
  // ...
}
app.get('/users', getUsers);
app.post('/users', createUser);

The path is still the same, /users, but if we make a POST request to that URL, the application will try to create a new user. Otherwise, if the method is GET, it will return a list of all the registered members. There is also a method, app.all, which we can use to handle all the method...