18.05.2016 Views

Mittwoch, 18. Mai, 2016

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Delving into Node.js and Express web framework 37<br />

Controller<br />

Now, in the app/controllers folder, create a file named index.server.controller.js with the<br />

following lines of code:<br />

1 exports.render = function(req, res) {<br />

2 res.send('Howdy World');<br />

3 };<br />

Here we’re using a CommonJS module pattern to define a function named render() which we’ll<br />

then later use to require this module and use its function.<br />

Express routing<br />

Once we’ve created a controller, we’ll need to use Express routing functionality to make use of this<br />

controller. Express routing example is shown in the following code snippet:<br />

1 app.get('/', function(req, res) {<br />

2 res.send('This is a GET request');<br />

3 });<br />

This tells Express to execute the middleware function for any HTTP request that comes through a<br />

GET method and is directed to the root path (‘/’). If we would need to deal with POST requests, we<br />

would simply use app.post.<br />

Express can chain several middlewares in a single routing definition, which means that middleware<br />

functions will be called in order. This is usually used to validate requests before executing the<br />

response logic. To understand this better, lets take a look at the following example:<br />

1 var port = 1337;<br />

2 var express = require('express');<br />

3<br />

4 var nameExists = function(req, res, next) {<br />

5 if (req.param('name')) {<br />

6 next();<br />

7 }<br />

8 else {<br />

9 res.send('What is your name?');<br />

10 }<br />

11 };<br />

12<br />

13 var sayHowdy = function(req, res, next) {

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!