-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson-server.js
More file actions
42 lines (35 loc) · 908 Bytes
/
json-server.js
File metadata and controls
42 lines (35 loc) · 908 Bytes
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
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();
const port = 3100;
const jwtToken = `AJWTToken`;
const isAuthorized = (req) => {
let bearer = req.get('Authorization');
if (bearer === 'Bearer ' + jwtToken) {
return true;
}
return false;
}
server.use(middlewares);
server.post('/sign-in', (req, res) => {
const username = req.body.username;
const password = req.body.password;
if (username === 'demo' && password === 'demo') {
res.json({
name: 'demo',
token: jwtToken
});
}
res.send(422, 'Invalid username and password');
});
server.use((req, res, next) => {
if (isAuthorized(req)) next();
else {
res.sendStatus(401);
}
});
server.use(router);
server.listen(port, () => {
console.log(`JSON Server is running on port ${port}`);
});