refactored format example
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tj Holowaychuk · committed by Tj Holowaychuk · parent c1cfd4a · Browse files · 1 file·+38 added−34 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+38 added−34 removed
- other:+38 added−34 removed
Provenance
- Commit
540192f- Tree
f568317- Author
Tj Holowaychuk <tj@vision-media.ca>- Committer
Tj Holowaychuk <tj@vision-media.ca>- Parent
c1cfd4a
1 file changed+38 added−34 removed
modified:examples/format/app.js+38 added-34 removed
8 unmodified lines9101112131415131415161718192021212223242526272825262728293031323334353637383940414243444546474849505152535429303132333435363738394041424344454647484950515253545556575859606162634 unmodified lines8 unmodified lines
// Fake items
var items = [ { name: 'foo' }, { name: 'bar' }, { name: 'baz' } { name: 'foo' } , { name: 'bar' } , { name: 'baz' }];
// Routes
app.get('/', function(req, res, next){ res.send('Visit /item/2'); res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<p>Visit /item/2</p>'); res.write('<p>Visit /item/2.json</p>'); res.write('<p>Visit /item/2.xml</p>'); res.end();});
app.get('/item/:id.:format?', function(req, res, next){ var id = req.params.id, format = req.params.format, item = items[id]; // Ensure item exists if (item) { // Serve the format switch (format) { case 'json': // Detects json res.send(item); break; case 'xml': // Set contentType as xml then sends // the string var xml = '' + '<items>' + '<item>' + item.name + '</item>' + '</items>'; res.contentType('.xml'); res.send(xml); break; case 'html': default: // By default send some hmtl res.send('<h1>' + item.name + '</h1>'); } } else { // We could simply pass route control and potentially 404 // by calling next(), or pass an exception like below. next(new Error('Item ' + id + ' does not exist')); var id = req.params.id , format = req.params.format , item = items[id]; // Ensure item exists if (item) { // Serve the format switch (format) { case 'json': // Detects json res.send(item); break; case 'xml': // Set contentType as xml then sends // the string var xml = '' + '<items>' + '<item>' + item.name + '</item>' + '</items>'; res.contentType('.xml'); res.send(xml); break; case 'html': default: // By default send some hmtl res.send('<h1>' + item.name + '</h1>'); } } else { // We could simply pass route control and potentially 404 // by calling next(), or pass an exception like below. next(new Error('Item ' + id + ' does not exist')); }});
// Middleware
4 unmodified lines