Attempt for better connection indicators
[vchess.git] / server / app.js
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');
8
9 let app = express();
10
11 app.use(favicon(path.join(__dirname, "static", "favicon.ico")));
12
13 if (app.get('env') === 'development')
14 // Full logging in development mode
15 app.use(logger('dev'));
16 else {
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 }));
23 }
24
25 app.use(express.json());
26 app.use(express.urlencoded({ extended: false }));
27 app.use(cookieParser());
28 // Client "prod" files:
29 app.use(express.static(path.join(__dirname, 'static')));
30 // Update in progress:
31 app.use(express.static(path.join(__dirname, 'fallback')));
32
33 // In development stage the client side has its own server
34 if (params.cors.enable) {
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
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 );
46 next();
47 });
48 }
49
50 // Routing (AJAX-only)
51 const routes = require(path.join(__dirname, "routes", "all"));
52 app.use('/', routes);
53
54 // Catch 404 and forward to error handler
55 app.use(function(req, res, next) {
56 next(createError(404));
57 });
58
59 // Error handler
60 app.use(function(err, req, res, next) {
61 res.status(err.status || 500);
62 if (app.get('env') === 'development') console.log(err.stack);
63 res.send(
64 "<h1>" + err.message + "</h1>" +
65 "<h2>" + err.status + "</h2>"
66 );
67 });
68
69 module.exports = app;