-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
70 lines (57 loc) · 1.94 KB
/
server.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
70
'use strict';
require('node-jsx').install({ extension: '.jsx' });
var http = require('http');
var router = require('routes')();
var ejs = require('ejs');
var fs = require('fs');
var ecstatic = require('ecstatic')(__dirname + '/static');
var serialize = require('serialize-javascript');
var renderAppToString = require('./lib/renderAppToString');
var products = require('./data/products');
var categories = require('./data/categories');
var ejsTemplate = fs.readFileSync(__dirname + '/views/index.ejs', 'utf8');
// Routes
router.addRoute('/', function (req, res) {
var stateOutput = {};
// Set the categories.
stateOutput.categories = categories;
// Render the React application in the ejs template.
renderAppToString(req.url, { categories: categories }, function (html) {
res.write(ejs.render(ejsTemplate, {
appOutput: html,
stateOutput: 'window.App=' + serialize(stateOutput) + ';'
}));
res.end();
});
});
router.addRoute('/products/:product', function (req, res, params) {
var stateOutput = {};
// Set the categories and products.
stateOutput.categories = categories;
stateOutput.products = products[params.product];
// Render the React application in the ejs template.
renderAppToString(req.url, { categories: categories, products: stateOutput.products }, function (html) {
res.write(ejs.render(ejsTemplate, {
appOutput: html,
stateOutput: 'window.App=' + serialize(stateOutput) + ';'
}));
res.end();
});
});
// Route for API.
router.addRoute('/api/products/:category', function (req, res, params) {
res.setHeader('content-type', 'application/json');
res.write(serialize(products[params.category]));
res.end();
});
var server = http.createServer(function (req, res) {
var m = router.match(req.url);
if (m) {
m.fn(req, res, m.params);
} else {
ecstatic(req, res);
}
});
server.listen(5000, function () {
console.log('listening on :' + server.address().port);
});