Created
February 28, 2019 22:00
-
-
Save smashercosmo/860afc5e3005e6bdcc9a3ba4e21847d2 to your computer and use it in GitHub Desktop.
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
const { StaticRouter } = require('react-router-dom') | |
const https = require('https') | |
const http = require('http') | |
const express = require('express') | |
const bodyParser = require('body-parser') | |
const React = require('react') | |
const { renderToString } = require('react-dom/server') | |
const path = require('path') | |
const fs = require('fs') | |
const PROJECT_DIR = __dirname | |
const ADDRESS = '0.0.0.0' | |
const PORT = process.env.PORT || 8080 | |
const app = express() | |
const server = http.createServer(app) | |
function render({ App }) { | |
const appComponent = React.createElement(App, {}, null) | |
const staticRouter = React.createElement( | |
StaticRouter, | |
{ location: url, context }, | |
appComponent, | |
) | |
return renderToString(staticRouter) | |
} | |
function getBundleModule(res, url, callback) { | |
const protocol = url.substr(0, 5) === 'https' ? https : http | |
const fileName = url.match(/.*\/(.*\.js)$/)[1] | |
const filePath = path.join(PROJECT_DIR, fileName) | |
if (fs.existsSync(url)) { | |
callback(require(url)) | |
} else { | |
protocol | |
.get(url, response => { | |
if (response.statusCode === 200) { | |
const file = fs.createWriteStream(filePath) | |
response.pipe(file) | |
file.on('finish', () => { | |
file.close(() => callback(require(filePath))) | |
}) | |
} | |
}) | |
.on('error', error => { | |
res.status(500).send(error) | |
}) | |
} | |
} | |
app.use(bodyParser.json()) | |
app.get('/render', (req, res) => { | |
const { fileUrl } = req.body | |
getBundleModule(res, fileUrl, async bundleModule => { | |
try { | |
const html = render({ App }) | |
res.json({ html }) | |
} catch (error) { | |
return res.status(500).send(error.message) | |
} | |
}) | |
}) | |
server.listen(PORT, ADDRESS, () => { | |
console.log(`React render server listening at http://${ADDRESS}:${PORT}`) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment