app.js
This file
Path
examples/format/app.js
71 lines · 1.6 KiB · JavaScript
Last changed by
fixing more examplesTj Holowaychukbefore adoption66a6214
History of this fileTake it
The walk stopped after 200 commits: lines older than e958988 point at it.
styling for stylus exampleTj Holowaychukbefore adoptione958988
line 1why, one step back1fixing more examplesTj Holowaychukbefore adoption66a6214
lines 2–4why, one step back2// Expose modules in ./support for demo purposes3require.paths.unshift(__dirname + '/../../support');4styling for stylus exampleTj Holowaychukbefore adoptione958988
lines 5–23why, one step back5/**6 * Module dependencies.7 */89var express = require('../../lib/express');1011var app = express.createServer();1213// Fake items1415var items = [16 { name: 'foo' }17 , { name: 'bar' }18 , { name: 'baz' }19];2021// Routes2223app.get('/', function(req, res, next){fixing more examplesTj Holowaychukbefore adoption66a6214
lines 24–25why, one step back24 res.statusCode = 200;25 res.setHeader('Content-Type', 'text/html');styling for stylus exampleTj Holowaychukbefore adoptione958988
lines 26–71why, one step back26 res.write('<p>Visit /item/2</p>');27 res.write('<p>Visit /item/2.json</p>');28 res.write('<p>Visit /item/2.xml</p>');29 res.end();30});3132app.get('/item/:id.:format?', function(req, res, next){33 var id = req.params.id34 , format = req.params.format35 , item = items[id];36 // Ensure item exists37 if (item) {38 // Serve the format39 switch (format) {40 case 'json':41 // Detects json42 res.send(item);43 break;44 case 'xml':45 // Set contentType as xml then sends46 // the string47 var xml = ''48 + '<items>'49 + '<item>' + item.name + '</item>'50 + '</items>';51 res.contentType('.xml');52 res.send(xml);53 break;54 case 'html':55 default:56 // By default send some hmtl57 res.send('<h1>' + item.name + '</h1>');58 }59 } else {60 // We could simply pass route control and potentially 40461 // by calling next(), or pass an exception like below.62 next(new Error('Item ' + id + ' does not exist'));63 }64});6566// Middleware6768app.use(express.errorHandler({ showStack: true }));6970app.listen(3000);71console.log('Express app started on port 3000');