-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
56 lines (49 loc) · 1.68 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// server.js
var express = require('express')
var path = require('path')
var compression = require('compression')
import React from 'react'
import {renderToString} from 'react-dom/server'
import {match, RouterContext} from 'react-router'
import routes from './modules/routes'
var app = express()
app.use(compression())
//serve our static stuff like index.css
app.use(express.static(path.join(__dirname,'public'), {index: false}))
function renderPage(appHtml){
return `
<!DOCTYPE html public="storage">
<html>
<meta charset=utf-8/>
<title>My Awesome React Router App</title>
<link rel=stylesheet href="/index.css"/>
<div id="app">${appHtml}</div>
<script src="/bundle.js"></script>
</html>
`
}
app.get('*', (req, res) => {
match({ routes: routes, location: req.url }, (err, redirect, props) => {
// in here we can make some decisions all at once
if (err) {
// there was an error somewhere during route matching
res.status(500).send(err.message)
} else if (redirect) {
// we haven't talked about `onEnter` hooks on routes, but before a
// route is entered, it can redirect. Here we handle on the server.
res.redirect(redirect.pathname + redirect.search)
} else if (props) {
// if we got props then we matched a route and can render
//console.log(props)
const appHtml = renderToString(<RouterContext {...props}/>)
res.send(renderPage(appHtml))
} else {
// no errors, no redirect, we just didn't match anything
res.status(404).send('Not Found')
}
})
})
var PORT = process.env.PORT || 3000
app.listen(PORT, function(){
console.log('Production Express server running at localhost:'+PORT)
})