-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
90 lines (71 loc) · 2.61 KB
/
Copy pathserver.js
File metadata and controls
90 lines (71 loc) · 2.61 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import fs from 'fs';
import path from 'path';
import React from 'react';
import express from 'express';
import bodyParser from 'body-parser';
import compression from 'compression';
import serialize from 'serialize-javascript';
import ReactDOMServer from 'react-dom/server';
import { StaticRouter, matchPath } from 'react-router-dom';
import Routes from './src/routes';
import App from './src/App';
const app = express();
var cfg = JSON.parse(fs.readFileSync('config.json', 'utf8'));
global.ConfigApp = cfg[cfg.env];
if (ConfigApp.logger) app.use(require('morgan')('dev'));
app.use(express.static('./build'));
app.use(compression());
app.use(bodyParser.json({ limit: '50mb', type: '*/*' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: false }));
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.get('/pricing', function (req, res) {
res.json({ message: 'TEST!!!' })
});
app.get('/*', (req, res) => {
const currentRoute =
Routes.find(route => matchPath(req.url, route)) || {};
let promise;
if (currentRoute.loadData) {
promise = currentRoute.loadData();
} else {
promise = Promise.resolve(null);
}
promise.then(data => {
const context = { data };
const app = ReactDOMServer.renderToString(
<StaticRouter location={req.url} context={context}>
<App />
</StaticRouter>
);
const indexFile = path.resolve('./build/index.html');
fs.readFile(indexFile, 'utf8', (err, indexData) => {
if (err) {
console.error('Something went wrong:', err);
return res.status(500).send('Oops, better luck next time!');
}
if (context.status === 404) {
res.status(404);
}
if (context.url) {
return res.redirect(301, context.url);
}
return res.send(
indexData
.replace('<div id="root"></div>', `<div id="root">${app}</div>`)
.replace(
'</body>',
`<script>window.__ROUTE_DATA__ = ${serialize(data)}</script></body>`
)
);
});
});
});
app.listen(ConfigApp.port, function () {
console.log(`😎 Server is listening on port ${ConfigApp.port} !`);
})