Skip to content
Myr

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 file

Take it

The walk stopped after 200 commits: lines older than 578fddc point at it.

cache view contents againTj Holowaychukbefore adoption578fddc

line 1why, one step back
1

fixing more examplesTj Holowaychukbefore adoption66a6214

lines 2–4why, one step back
2// Expose modules in ./support for demo purposes
3require.paths.unshift(__dirname + '/../../support');4

cache view contents againTj Holowaychukbefore adoption578fddc

lines 5–15why, one step back
5/**
6 * Module dependencies.7 */89var express = require('../../lib/express');1011var app = express.createServer();1213// Fake items1415var items = [

refactored format exampleTj Holowaychukbefore adoption540192f

lines 16–18why, one step back
16 { name: 'foo' }
17 , { name: 'bar' }18 , { name: 'baz' }

cache view contents againTj Holowaychukbefore adoption578fddc

lines 19–23why, one step back
19];
2021// Routes2223app.get('/', function(req, res, next){

fixing more examplesTj Holowaychukbefore adoption66a6214

lines 24–25why, one step back
24 res.statusCode = 200;
25 res.setHeader('Content-Type', 'text/html');

refactored format exampleTj Holowaychukbefore adoption540192f

lines 26–29why, one step back
26 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();

cache view contents againTj Holowaychukbefore adoption578fddc

lines 30–32why, one step back
30});
3132app.get('/item/:id.:format?', function(req, res, next){

refactored format exampleTj Holowaychukbefore adoption540192f

lines 33–57why, one step back
33 var id = req.params.id
34 , 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>');

cache view contents againTj Holowaychukbefore adoption578fddc

line 58why, one step back
58 }

refactored format exampleTj Holowaychukbefore adoption540192f

lines 59–63why, one step back
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 }

cache view contents againTj Holowaychukbefore adoption578fddc

lines 64–71why, one step back
64});
6566// Middleware6768app.use(express.errorHandler({ showStack: true }));6970app.listen(3000);71console.log('Express app started on port 3000');