Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
60 lines (52 loc) · 1.8 KB
/
Copy pathserver.js
File metadata and controls
60 lines (52 loc) · 1.8 KB
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
57
58
59
60
import path from 'path'
import { Server } from 'http'
import Express from 'express'
import React from 'react'
import { renderToString } from 'react-dom/server'
import { match, RouterContext } from 'react-router'
import routes from './src/routes'
import NotFoundPage from './src/modules/notfound'
// initialize the server and configure support for ejs templates
const app = new Express()
const server = new Server(app)
app.set('view engine', 'ejs')
app.set('views', path.join(__dirname, 'config'))
// define the folder that will be used for static assets
app.use(Express.static(path.join(__dirname, 'dist')))
// universal routing and rendering
app.get('*', (req, res) => {
match(
{ routes, location: req.url },
(err, redirectLocation, renderProps) => {
// in case of error display the error message
if (err) {
return res.status(500).send(err.message)
}
// in case of redirect propagate the redirect to the browser
if (redirectLocation) {
return res.redirect(302, redirectLocation.pathname + redirectLocation.search)
}
// generate the React markup for the current route
let markup;
if (renderProps) {
// if the current route matched we have renderProps
markup = renderToString(<RouterContext {...renderProps}/>)
} else {
// otherwise we can render a 404 page
markup = renderToString(<NotFoundPage/>)
res.status(404);
}
// render the index template with the embedded React markup
return res.render('index', { markup })
}
);
});
// start the server
const port = process.env.PORT || 3000
const env = process.env.NODE_ENV || 'production'
server.listen(port, err => {
if (err) {
return console.error(err)
}
console.info(`Server running on http://localhost:${port} [${env}]`)
});