Replaced AJAX by fetch: not everything tested yet, but seems fine
[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 {
15 // Full logging in development mode
16 app.use(logger('dev'));
17 }
18 else
19 {
20 // http://dev.rdybarra.com/2016/06/23/Production-Logging-With-Morgan-In-Express/
21 app.set('trust proxy', true);
22 // In prod, only log error responses (https://github.com/expressjs/morgan)
23 app.use(logger('combined', {
24 skip: function (req, res) { return res.statusCode < 400 }
25 }));
26 }
27
28 app.use(express.json());
29 app.use(express.urlencoded({ extended: false }));
30 app.use(cookieParser());
31 // Client "prod" files:
32 app.use(express.static(path.join(__dirname, 'static')));
33 // Update in progress:
34 app.use(express.static(path.join(__dirname, 'while_update')));
35
36 // In development stage the client side has its own server
37 if (params.cors.enable)
38 {
39 app.use(function(req, res, next) {
40 res.header("Access-Control-Allow-Origin", params.cors.allowedOrigin);
41 res.header("Access-Control-Allow-Credentials", true); //for cookies
42 res.header(
43 "Access-Control-Allow-Headers",
44 "Origin, X-Requested-With, Content-Type, Accept"
45 );
46 res.header(
47 "Access-Control-Allow-Methods",
48 "GET, POST, OPTIONS, PUT, DELETE"
49 );
50 next();
51 });
52 }
53
54 // Routing (AJAX-only)
55 const routes = require(path.join(__dirname, "routes", "all"));
56 app.use('/', routes);
57
58 // Catch 404 and forward to error handler
59 app.use(function(req, res, next) {
60 next(createError(404));
61 });
62
63 // Error handler
64 app.use(function(err, req, res, next) {
65 res.status(err.status || 500);
66 if (app.get('env') === 'development')
67 console.log(err.stack);
68 res.send(
69 "<h1>" + err.message + "</h1>" +
70 "<h2>" + err.status + "</h2>"
71 );
72 });
73
74 module.exports = app;