Skip to content
Myr

app.js

This file

Path

examples/format/app.js

62 lines · 1.4 KiB · JavaScript

Last changed by

Merge branch 'format-example'Tj Holowaychukbefore adoption5dbd1a6

History of this file

Take it

Merge branch 'format-example'Tj Holowaychukbefore adoption5dbd1a6

lines 1–62why, one step back
1
2/**3 * Module dependencies.4 */56var express = require('../../lib/express');78var app = express.createServer();910// Fake items1112var items = [13 { name: 'foo' },14 { name: 'bar' },15 { name: 'baz' }16];1718// Routes1920app.get('/', function(req, res, next){21 res.send('Visit /item/2');22});2324app.get('/item/:id.:format?', function(req, res, next){25 var id = req.params.id,26 format = req.params.format,27 item = items[id];28 // Ensure item exists29 if (item) {30 // Serve the format31 switch (format) {32 case 'json':33 // Detects json34 res.send(item);35 break;36 case 'xml':37 // Set contentType as xml then sends38 // the string39 var xml = ''40 + '<items>'41 + '<item>' + item.name + '</item>'42 + '</items>';43 res.contentType('.xml');44 res.send(xml);45 break;46 case 'html':47 default:48 // By default send some hmtl49 res.send('<h1>' + item.name + '</h1>');50 }51 } else {52 // We could simply pass route control and potentially 40453 // by calling next(), or pass an exception like below.54 next(new Error('Item ' + id + ' does not exist'));55 }56});5758// Middleware5960app.use(express.errorHandler({ showStack: true }));6162app.listen(3000);