Refactor Problems view: should now handle better long problems lists
[vchess.git] / server / app.js
CommitLineData
c5c47010
BA
1const createError = require('http-errors');
2const express = require('express');
3const path = require('path');
4const cookieParser = require('cookie-parser');
5const logger = require('morgan');
6const favicon = require('serve-favicon');
7const params = require('./config/parameters');
625022fd 8
c5c47010 9let app = express();
625022fd 10
98db2082 11app.use(favicon(path.join(__dirname, "static", "favicon.ico")));
625022fd
BA
12
13if (app.get('env') === 'development')
dac39588
BA
14 // Full logging in development mode
15 app.use(logger('dev'));
0234201f 16else {
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
25app.use(express.json());
26app.use(express.urlencoded({ extended: false }));
27app.use(cookieParser());
e57c4de4
BA
28// Client "prod" files:
29app.use(express.static(path.join(__dirname, 'static')));
30// Update in progress:
7c42b2ff 31app.use(express.static(path.join(__dirname, 'fallback')));
625022fd
BA
32
33// In development stage the client side has its own server
0234201f 34if (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)
51const routes = require(path.join(__dirname, "routes", "all"));
52app.use('/', routes);
53
e57c4de4 54// Catch 404 and forward to error handler
625022fd
BA
55app.use(function(req, res, next) {
56 next(createError(404));
57});
58
e57c4de4 59// Error handler
625022fd 60app.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
69module.exports = app;