forked from 3rgo/node_api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
47 lines (39 loc) · 1.11 KB
/
Copy pathserver.js
File metadata and controls
47 lines (39 loc) · 1.11 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
/* eslint-disable no-console */
const express = require('express');
const bodyParser = require('body-parser');
const API_KEY = "8f94826adab8ffebbeadb4f9e161b2dc";
const Routes = require('./route');
const app = express();
const requireJsonContent = () => {
return (req, res, next) => {
if (req.headers['content-type'] !== 'application/json') {
res.status(400).send('Server requires application/json')
} else {
next()
}
}
}
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const HTTP_PORT = 8000;
app.listen(HTTP_PORT, () => {
console.log(`Server running on port ${HTTP_PORT}`);
});
// Basic route
app.get('/', (req, res) => {
res.json({ message: 'Hello World' });
});
app.post('/', requireJsonContent(), (req, res, next) => {
res.send('You sent JSON');
})
// Routes
app.use('/api', Routes);
// PROTECT ALL ROUTES THAT FOLLOW
app.use((req, res, next) => {
const apiKey = req.get('Authorization')
if (!apiKey || apiKey !== `Bearer ${API_KEY}`) {
res.status(401).json({error: 'unauthorised'})
} else {
next()
}
})