Create a gist now

Instantly share code, notes, and snippets.

@bradparker /index.js
Last active Feb 27, 2017

Embed
What would you like to do?
const URL = require('url')
const QS = require('qs')
const { createElement } = require('react')
const { renderToString } = require('react-dom/server')
const { createServer } = require('http')
const logger = require('connect-logger')
const connect = require('connect')
const components = require('./components')
const PORT = process.env.PORT || 8080
const app = connect()
app.use(logger())
app.use('/', (request, response) => {
const { url } = request
const { query } = URL.parse(url)
const { name, props } = QS.parse(query)
const component = components[name]
if (!component) {
response.statusCode = 404
return response.end(JSON.stringify({
error: { message: 'Unknown component' }
}))
}
response.statusCode = 200
response.end(JSON.stringify({
content: renderToString(
createElement(component, props)
)
}))
})
const server = createServer(app).listen(PORT, () => {
const { address, port } = server.address()
console.log(`View server listening on ${address}:${port}`)
})
{
"name": "view-server",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"connect": "^3.6.0",
"connect-logger": "^0.0.1",
"qs": "^6.3.1",
"react": "^15.4.2",
"react-dom": "^15.4.2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment