18.05.2016 Views

Mittwoch, 18. Mai, 2016

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

1 var port = 1337;<br />

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

3 var app = connect();<br />

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

5 console.log(req.method, req.url);<br />

6 next();<br />

7 };<br />

8<br />

9 var howdyWorld= function(req, res, next) {<br />

10 res.setHeader('Content-Type', 'text/plain');<br />

11 res.end('Howdy World');<br />

12 };<br />

13<br />

14 app.use(logger);<br />

15 app.use('/howdy', howdyWorld);<br />

16<br />

17 app.listen(port);<br />

18 console.log('Server running at http://localhost:' + port);<br />

The logger() middleware uses the console.log() method to log the method and url of the request<br />

(req variable) out to the console. The logger() middleware is registered before the howdyWorld()<br />

middleware because that determines the order in which each middlewares are executed. Another<br />

thing to notice is the next() call in the logger() middleware, which then calls the howdyWorld()<br />

middleware. Removing the next() call would stop the execution of middleware function at the<br />

logger() middleware, which would in turn mean that the request would hang forever as the response<br />

would never end by calling the res.end() method. Finally, the howdyWorld() middleware is bound<br />

to respond only to requests made to the /howdy path.<br />

Express<br />

Since Connect module is open source, it can be extended and one (yeah, you heard that right -<br />

one, uno, jedan, ein) developer named TJ Holowaychuk did it better than most when he released a<br />

Connect-based web framework known as Express⁷⁷. I’ll summarize TJ Holowaychuk like this:<br />

⁷⁷http://expressjs.com

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

Saved successfully!

Ooh no, something went wrong!