Created
February 13, 2015 02:36
-
-
Save minipai/3b9e12c3429bb5f725b6 to your computer and use it in GitHub Desktop.
Express middleware to render react.js on server side, with react-router
This file contains hidden or 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 React = require('react'); | |
var Router = require('react-router'); | |
var DocumentTitle = require('react-document-title'); | |
var reactRoutes = require('../view/_route.jsx'); | |
var Html = require('../view/Html.jsx'); | |
/** | |
* @name RenderView | |
* @constructor | |
*/ | |
function RenderView() { | |
} | |
/** | |
* Middleware function for express or connect server. | |
*/ | |
RenderView.prototype.middleware = function() { | |
console.info('RenderView.prototype.middleware'); | |
return function(req, res, next) { | |
res.renderView = function(){ | |
console.info('res.renderView'); | |
var req = this.req; | |
res.format({ | |
'text/html': function(){ | |
if(res.statusCode == 303) { | |
res.redirect(req.session.history[1]) | |
return | |
} | |
try { | |
Router.run(reactRoutes, req.url, function (Handler, state) { | |
var title = DocumentTitle.rewind(); | |
var body = React.renderToString(React.createElement(Handler, React.__spread({}, req.data))); | |
var html = React.renderToString(React.createElement(Html, {title: req.data.title, body: body})); | |
res.send('<!DOCTYPE html>' + html); | |
res.end() | |
}); | |
} catch(err) { | |
console.info('catch err@text/html'); | |
return req.next(err) | |
} | |
}, | |
'application/json': function(){ | |
res.json(req.data) | |
}, | |
'default': function() { | |
res.status(406).send('Not Acceptable'); | |
} | |
}); | |
}; | |
next() | |
} | |
}; | |
module.exports = new RenderView; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment