server.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import express from 'express'
  2. import path from 'path'
  3. import compression from 'compression'
  4. import React from 'react'
  5. import { renderToString } from 'react-dom/server'
  6. import { match, RouterContext } from 'react-router'
  7. import routes from './modules/routes'
  8. var app = express()
  9. app.use(compression())
  10. // serve our static stuff like index.css
  11. app.use(express.static(path.join(__dirname, 'public')))
  12. // send all requests to index.html so browserHistory works
  13. app.get('*', (req, res) => {
  14. match({ routes, location: req.url }, (err, redirect, props) => {
  15. if (err) {
  16. res.status(500).send(err.message)
  17. } else if (redirect) {
  18. res.redirect(redirect.pathname + redirect.search)
  19. } else if (props) {
  20. // hey we made it!
  21. const appHtml = renderToString(<RouterContext {...props}/>)
  22. res.send(renderPage(appHtml))
  23. } else {
  24. res.status(404).send('Not Found')
  25. }
  26. })
  27. })
  28. function renderPage(appHtml) {
  29. return `
  30. <!doctype html public="storage">
  31. <html>
  32. <meta charset=utf-8/>
  33. <title>My First React Router App</title>
  34. <link rel=stylesheet href=/index.css>
  35. <div id=app>${appHtml}</div>
  36. <script src="/bundle.js"></script>
  37. `
  38. }
  39. var PORT = process.env.PORT || 8080
  40. app.listen(PORT, function() {
  41. console.log('Production Express server running at localhost:' + PORT)
  42. })