Last active
August 29, 2015 14:07
-
-
Save killercup/6f1b66f0496eca6e4d11 to your computer and use it in GitHub Desktop.
Render React in Express App, Set HTTP Status
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var path = require('path'); | |
var express = require('express'); | |
var l = require('lodash'); | |
var gutil = require('gulp-util'); | |
var React = require('react'); | |
var App = require('./index'); | |
var STATIC_PATH = path.join(__dirname, '../build'); | |
var TEMPLATE_PATH = path.join(STATIC_PATH, 'template.html'); | |
var render = (function () { | |
var template; | |
template = require('fs').readFileSync(TEMPLATE_PATH); | |
return l.template(template, null, { | |
variabled: 'data' | |
}); | |
})(); | |
var server = express(); | |
server.use('/static', express.static(STATIC_PATH)); | |
server.use(function renderReact (req, res, next) { | |
var error, page, statusCodeColor; | |
try { | |
page = App({ | |
path: req.path, | |
setHTTPStatus: function(code) { | |
if (code != null) { | |
return res.status(code); | |
} | |
} | |
}); | |
res.send(render({ | |
data: { | |
html: React.renderComponentToString(page) | |
} | |
})); | |
} catch (_error) { | |
error = _error; | |
return next(error); | |
} | |
statusCodeColor = res.statusCode === 200 ? 'green' : 'red'; | |
return gutil.log(gutil.colors[statusCodeColor]("[" + res.statusCode + "]"), "GET", req.path); | |
}); | |
server.use(function logError (err, req, res, next) { | |
gutil.log(gutil.colors.red("[ERROR]"), req.path); | |
return next(err); | |
}); | |
var port = process.env.NODE_PORT || 3000; | |
server.listen(port, function hello () { | |
return gutil.log("Server listening at http://localhost:" + port + "/"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment