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...