-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
74 lines (63 loc) · 2.41 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
71
72
73
74
'use strict';
require('node-jsx').install({harmony: true});
var express = require('express');
var favicon = require('serve-favicon');
var serialize = require('serialize-javascript');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var csrf = require('csurf');
var navigateAction = require('flux-router-component').navigateAction;
var debug = require('debug')('Example');
var React = require('react');
var app = require('./src/app.js');
var HtmlComponent = React.createFactory(require('./src/views/Html.jsx'));
var server = express();
server.set('state namespace', 'App');
server.use(favicon(__dirname + '/images/favicons/favicon.ico'));
server.use('/public', express.static(__dirname + '/public'));
server.use('/images', express.static(__dirname + '/images'));
server.use('/bower_components', express.static(__dirname + '/bower_components'));
server.use(cookieParser());
server.use(bodyParser.json());
server.use(csrf({cookie: true}));
var fetchrPlugin = app.getPlugin('FetchrPlugin');
fetchrPlugin.registerService(require('./src/services/feed'));
server.use(fetchrPlugin.getXhrPath(), fetchrPlugin.getMiddleware());
server.use(function (req, res, next) {
var context = app.createContext({
req: req, // The fetchr plugin depends on this
xhrContext: {
_csrf: req.csrfToken() // Make sure all XHR requests have the CSRF token
}
});
debug('Executing navigate action');
context.getActionContext().executeAction(navigateAction, {
url: req.url
}, function (err) {
if (err) {
if (err.status && err.status === 404) {
next();
} else {
next(err);
}
return;
}
debug('Exposing context state');
var exposed = 'window.App=' + serialize(app.dehydrate(context)) + ';';
debug('Rendering Application component into html');
var AppComponent = app.getAppComponent();
var html = React.renderToStaticMarkup(HtmlComponent({
state: exposed,
context: context.getComponentContext(),
markup: React.renderToString(AppComponent({
context: context.getComponentContext()
}))
}));
debug('Sending markup');
res.write(html);
res.end();
});
});
var port = process.env.PORT || 4444;
server.listen(port);
console.log('Listening on port ' + port);