-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
56 lines (48 loc) · 1.52 KB
/
server.ts
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
import express, { NextFunction, Request, Response } from 'express';
import cors from 'cors';
import 'dotenv/config'
import morgan from 'morgan';
import { ALLOWED_ORIGINS, EXPRESS_PORT } from './config';
import Router from './routes';
import authenticate from './middleware/authenticate';
const app = express();
const corsOptions: cors.CorsOptions = {
origin: (origin, callback) => {
if (!origin || ALLOWED_ORIGINS.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
methods: ['GET', 'POST', 'PUT', 'DELETE'],
credentials: true,
};
// restrict cors
app.use(cors(corsOptions));
// allow preflight requests
app.options('*', cors(corsOptions));
// trust nginx proxy
app.set('trust proxy', 1);
// log requests
app.use(morgan('dev'));
// parse json and urlencoded data
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// error handling middleware
app.use((error: Error, request: Request, response: Response, next: NextFunction) => {
if (error instanceof SyntaxError && 'body' in error) {
response.status(400).json({ error: 'Bad Request, Check for syntax errors or incorrect formatting' });
} else {
next(error);
}
});
app.get('/', authenticate, (request: Request, response: Response) => {
const tokenData = (request as any).tokenData;
if (tokenData) {
response.send(`Hello, ${tokenData.username}!`);
}
});
app.use('/', Router);
app.listen(EXPRESS_PORT, () => {
console.log(`Server is running on port ${EXPRESS_PORT}`);
});