forked from kaddopur/carweb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
58 lines (48 loc) · 1.73 KB
/
server.js
File metadata and controls
58 lines (48 loc) · 1.73 KB
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
'use strict';
/**
* This leverages Express to create and run the http server.
* A fluxible context is created and executes the navigateAction
* based on the URL. Once completed, the store state is dehydrated
* and the application is rendered via React.
*/
require('babel/register');
var express = require('express');
var serialize = require('serialize-javascript');
var navigateAction = require('flux-router-component').navigateAction;
var debug = require('debug')('carweb');
var React = require('react');
var app = require('./app');
var htmlComponent = React.createFactory(require('./components/Html.jsx'));
var server = express();
server.set('state namespace', 'App');
server.use('/public', express.static(__dirname + '/build'));
server.use(function (req, res, next) {
var context = app.createContext();
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 html = React.renderToStaticMarkup(htmlComponent({
context: context.getComponentContext(),
state: exposed,
markup: React.renderToString(context.createElement())
}));
debug('Sending markup');
res.write('<!DOCTYPE html>' + html);
res.end();
});
});
var port = process.env.PORT || 3000;
server.listen(port);
console.log('Listening on port ' + port);