-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
66 lines (51 loc) · 1.71 KB
/
app.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
'use strict';
const express = require('express');
const bodyParser = require('body-parser');
const config = require('config');
const fs = require('fs');
const cors = require('cors');
const app = express();
if (app.get('env') === 'production') {
app.set('trust proxy', 'loopback'); // http://expressjs.com/guide/behind-proxies.html
}
app.set('x-powered-by', false);
const log4js = require('log4js');
log4js.configure(config.logging.log4js);
const logger = log4js.getLogger(app.settings.env);
app.set('logger', logger);
app.set('config', config);
app.set('fs', fs);
app.set('util', require('./libs/util'));
app.set('middleware.authApiKey', require('./libs/middleware/authApiKey'));
// CORS
const corsOptions = config.api.cors;
const whitelist = [];
corsOptions.origin.forEach(function (pattern, i) {
whitelist.push(new RegExp(pattern, 'i'));
});
corsOptions.origin = function (origin, callback) {
let match = false;
whitelist.forEach((value) => {
if (value.test(origin)) {
match = true;
}
})
if (match || !origin) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
const corsMiddleware = cors(corsOptions);
app.use(corsMiddleware); // CORS
app.options('*', corsMiddleware); // Enable CORS preflight - https://github.com/expressjs/cors#enabling-cors-pre-flight
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(require('./libs/middleware/response'));
const routesPath = './routes/';
fs.readdirSync(routesPath).forEach(function (file) {
if (!file.match(/\.js$/)) return; // Exclude folders
require(routesPath + file)(app);
});
app.use(require('./libs/middleware/error'));
module.exports = app;