Revise server code + a few fixes in trnalsations and ComputerGame
[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')
14{
dac39588
BA
15 // Full logging in development mode
16 app.use(logger('dev'));
625022fd
BA
17}
18else
19{
dac39588
BA
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 }));
625022fd
BA
26}
27
28app.use(express.json());
29app.use(express.urlencoded({ extended: false }));
30app.use(cookieParser());
98db2082 31app.use(express.static(path.join(__dirname, 'static'))); //client "prod" files
625022fd
BA
32
33// In development stage the client side has its own server
98db2082 34if (params.cors.enable)
625022fd 35{
dac39588
BA
36 app.use(function(req, res, next) {
37 res.header("Access-Control-Allow-Origin", params.cors.allowedOrigin);
38 res.header("Access-Control-Allow-Credentials", true); //for cookies
1aeed627 39 res.header("Access-Control-Allow-Headers",
77fd7298 40 "Origin, X-Requested-With, Content-Type, Accept");
dac39588 41 res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
77fd7298 42 next();
dac39588 43 });
625022fd
BA
44}
45
46// Routing (AJAX-only)
47const routes = require(path.join(__dirname, "routes", "all"));
48app.use('/', routes);
49
50// catch 404 and forward to error handler
51app.use(function(req, res, next) {
52 next(createError(404));
53});
54
55// error handler
56app.use(function(err, req, res, next) {
625022fd 57 res.status(err.status || 500);
866842c3
BA
58 res.send(
59 "<h1>" + err.message + "</h1>" +
60 "<h2>" + err.status + "</h2>" +
61 "<pre>" + err.stack + "</pre>"
62 );
625022fd
BA
63});
64
65module.exports = app;