-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
40 lines (33 loc) · 1.05 KB
/
server.js
File metadata and controls
40 lines (33 loc) · 1.05 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
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const entryDir = './build';
const middlewares = jsonServer.defaults({ static: entryDir });
const PORT = process.env.PORT || 5000;
// Set default middlewares (logger, static, cors and no-cache)
server.use(middlewares);
server.get('/serviceWorker.js', (req, res) => {
res.sendFile(`${__dirname}/serviceWorker.js`);
});
server.use((req, res, next) => {
if (req.method === 'GET' && !(/\/api/.test(req.url))) {
res.sendFile(`${__dirname}/${entryDir}/index.html`);
} else {
next();
}
});
// To handle POST, PUT and PATCH you need to use a body-parser
// You can use the one used by JSON Server
server.use(jsonServer.bodyParser);
server.use((req, res, next) => {
if (req.method === 'POST') {
req.body.createdAt = Date.now();
}
// Continue to JSON Server router
next();
});
// Use default router
server.use('/api', router);
server.listen(PORT, () => {
console.log(`JSON Server is running on: http://localhost:${PORT}`);
});