-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
82 lines (73 loc) · 2.17 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
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
require('dotenv').config();
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;
const path = require('path');
const fs = require('fs');
const axios = require('axios');
const filePath = path.resolve(__dirname, './build', 'index.html');
async function fetchData(routeName) {
const data = fs.readFileSync(filePath, 'utf8');
try {
const response = await axios.get(
`${process.env.REACT_APP_API_URL}/pages/${routeName}`
);
return data
.replace(
/\$_TITLE_/g,
response.data.meta.title
? process.env.REACT_APP_TITLE
: response.data.meta.title
)
.replace(
/\$_DESCRIPTION_/g,
response.data.meta.description
? 'David Shallon, 1950-2000, was an Israeli conductor. He was music director in Düsseldorf, Jerusalem and Luxemburg and has two sons, Yuval and Jonathan.'
: response.data.meta.description
);
} catch (error) {
return data
.replace(/\$_TITLE_/g, 'Error | David Shallon')
.replace(
/\$_DESCRIPTION_/g,
'David Shallon, 1950-2000, was an Israeli conductor. He was music director in Düsseldorf, Jerusalem and Luxemburg and has two sons, Yuval and Jonathan.'
);
}
}
app.get('/', async (req, res) => {
try {
const result = await fetchData('start');
res.send(result);
} catch (err) {
console.log(err);
}
});
app.get('/:pathname', async (req, res, next) => {
try {
if (req.headers['sec-fetch-dest'] === 'document') {
const pathName = req.params.pathname;
const result = await fetchData(pathName);
res.send(result);
}
} catch (err) {
console.log(err);
}
next();
});
app.get('/:firstLevel/:pathname', async (req, res, next) => {
try {
if (req.headers['sec-fetch-dest'] === 'document') {
const pathName = req.params.pathname;
const result = await fetchData(pathName);
res.send(result);
}
} catch (err) {
console.log(err);
}
next();
});
app.use(express.static(path.resolve(__dirname, './build')));
app.get('*', (req, res) => {
res.sendFile(filePath);
});
app.listen(port, () => console.log(`Listening on port ${port}`));