-
Notifications
You must be signed in to change notification settings - Fork 14.1k
/
app.js
69 lines (58 loc) · 1.45 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* Module dependencies.
*/
var express = require('../../');
var app = module.exports = express();
// Fake items
var items = [
{ name: 'foo' }
, { name: 'bar' }
, { name: 'baz' }
];
// Routes
app.get('/', function(req, res, next){
res.statusCode = 200;
res.setHeader('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.type('xml').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
app.use(express.errorHandler());
if (!module.parent) {
app.listen(3000);
silent || console.log('Express started on port 3000');
}