Commit | Line | Data |
---|---|---|
c5c47010 BA |
1 | const createError = require('http-errors'); |
2 | const express = require('express'); | |
3 | const path = require('path'); | |
4 | const cookieParser = require('cookie-parser'); | |
5 | const logger = require('morgan'); | |
6 | const favicon = require('serve-favicon'); | |
7 | const params = require('./config/parameters'); | |
625022fd | 8 | |
c5c47010 | 9 | let app = express(); |
625022fd | 10 | |
98db2082 | 11 | app.use(favicon(path.join(__dirname, "static", "favicon.ico"))); |
625022fd BA |
12 | |
13 | if (app.get('env') === 'development') | |
dac39588 BA |
14 | // Full logging in development mode |
15 | app.use(logger('dev')); | |
0234201f | 16 | else { |
dac39588 BA |
17 | // http://dev.rdybarra.com/2016/06/23/Production-Logging-With-Morgan-In-Express/ |
18 | app.set('trust proxy', true); | |
19 | // In prod, only log error responses (https://github.com/expressjs/morgan) | |
20 | app.use(logger('combined', { | |
21 | skip: function (req, res) { return res.statusCode < 400 } | |
22 | })); | |
625022fd BA |
23 | } |
24 | ||
25 | app.use(express.json()); | |
26 | app.use(express.urlencoded({ extended: false })); | |
27 | app.use(cookieParser()); | |
e57c4de4 BA |
28 | // Client "prod" files: |
29 | app.use(express.static(path.join(__dirname, 'static'))); | |
30 | // Update in progress: | |
7c42b2ff | 31 | app.use(express.static(path.join(__dirname, 'fallback'))); |
625022fd BA |
32 | |
33 | // In development stage the client side has its own server | |
0234201f | 34 | if (params.cors.enable) { |
dac39588 BA |
35 | app.use(function(req, res, next) { |
36 | res.header("Access-Control-Allow-Origin", params.cors.allowedOrigin); | |
37 | res.header("Access-Control-Allow-Credentials", true); //for cookies | |
e57c4de4 BA |
38 | res.header( |
39 | "Access-Control-Allow-Headers", | |
40 | "Origin, X-Requested-With, Content-Type, Accept" | |
41 | ); | |
42 | res.header( | |
43 | "Access-Control-Allow-Methods", | |
44 | "GET, POST, OPTIONS, PUT, DELETE" | |
45 | ); | |
77fd7298 | 46 | next(); |
dac39588 | 47 | }); |
625022fd BA |
48 | } |
49 | ||
50 | // Routing (AJAX-only) | |
51 | const routes = require(path.join(__dirname, "routes", "all")); | |
52 | app.use('/', routes); | |
53 | ||
e57c4de4 | 54 | // Catch 404 and forward to error handler |
625022fd BA |
55 | app.use(function(req, res, next) { |
56 | next(createError(404)); | |
57 | }); | |
58 | ||
e57c4de4 | 59 | // Error handler |
625022fd | 60 | app.use(function(err, req, res, next) { |
625022fd | 61 | res.status(err.status || 500); |
0234201f | 62 | if (app.get('env') === 'development') console.log(err.stack); |
866842c3 BA |
63 | res.send( |
64 | "<h1>" + err.message + "</h1>" + | |
0da7d5b8 | 65 | "<h2>" + err.status + "</h2>" |
866842c3 | 66 | ); |
625022fd BA |
67 | }); |
68 | ||
69 | module.exports = app; |