app.js
This file
Path
examples/format/app.js
67 lines · 1.4 KiB · JavaScript
Last changed by
refactored format exampleTj Holowaychukbefore adoption540192f
History of this fileTake it
The walk stopped after 200 commits: lines older than ce2a18f point at it.
master is 2.0.0-preTj Holowaychukbefore adoptionce2a18f
lines 1–12why, one step back12/**3 * Module dependencies.4 */56var express = require('../../lib/express');78var app = express.createServer();910// Fake items1112var items = [refactored format exampleTj Holowaychukbefore adoption540192f
lines 13–15why, one step back13 { name: 'foo' }14 , { name: 'bar' }15 , { name: 'baz' }master is 2.0.0-preTj Holowaychukbefore adoptionce2a18f
lines 16–20why, one step back16];1718// Routes1920app.get('/', function(req, res, next){refactored format exampleTj Holowaychukbefore adoption540192f
lines 21–25why, one step back21 res.writeHead(200, { 'Content-Type': 'text/html' });22 res.write('<p>Visit /item/2</p>');23 res.write('<p>Visit /item/2.json</p>');24 res.write('<p>Visit /item/2.xml</p>');25 res.end();master is 2.0.0-preTj Holowaychukbefore adoptionce2a18f
lines 26–28why, one step back26});2728app.get('/item/:id.:format?', function(req, res, next){refactored format exampleTj Holowaychukbefore adoption540192f
lines 29–53why, one step back29 var id = req.params.id30 , format = req.params.format31 , item = items[id];32 // Ensure item exists33 if (item) {34 // Serve the format35 switch (format) {36 case 'json':37 // Detects json38 res.send(item);39 break;40 case 'xml':41 // Set contentType as xml then sends42 // the string43 var xml = ''44 + '<items>'45 + '<item>' + item.name + '</item>'46 + '</items>';47 res.contentType('.xml');48 res.send(xml);49 break;50 case 'html':51 default:52 // By default send some hmtl53 res.send('<h1>' + item.name + '</h1>');master is 2.0.0-preTj Holowaychukbefore adoptionce2a18f
line 54why, one step back54 }refactored format exampleTj Holowaychukbefore adoption540192f
lines 55–59why, one step back55 } else {56 // We could simply pass route control and potentially 40457 // by calling next(), or pass an exception like below.58 next(new Error('Item ' + id + ' does not exist'));59 }master is 2.0.0-preTj Holowaychukbefore adoptionce2a18f
lines 60–67why, one step back60});6162// Middleware6364app.use(express.errorHandler({ showStack: true }));6566app.listen(3000);67console.log('Express app started on port 3000');