Work on correspondance challenges system
[vchess.git] / server / app.js
CommitLineData
625022fd
BA
1var createError = require('http-errors');
2var express = require('express');
3var path = require('path');
4var cookieParser = require('cookie-parser');
5var logger = require('morgan');
6var favicon = require('serve-favicon');
b644ef7f 7var params = require('./config/parameters');
625022fd
BA
8
9var app = express();
10
98db2082 11app.use(favicon(path.join(__dirname, "static", "favicon.ico")));
625022fd
BA
12
13if (app.get('env') === 'development')
14{
15 // Full logging in development mode
16 app.use(logger('dev'));
17}
18else
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
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
BA
35{
36 app.use(function(req, res, next) {
98db2082 37 res.header("Access-Control-Allow-Origin", params.cors.allowedOrigin);
625022fd
BA
38 res.header("Access-Control-Allow-Headers",
39 "Origin, X-Requested-With, Content-Type, Accept");
40 next();
41 });
42}
43
44// Routing (AJAX-only)
45const routes = require(path.join(__dirname, "routes", "all"));
46app.use('/', routes);
47
48// catch 404 and forward to error handler
49app.use(function(req, res, next) {
50 next(createError(404));
51});
52
53// error handler
54app.use(function(err, req, res, next) {
55 // set locals, only providing error in development
56 res.locals.message = err.message;
57 res.locals.error = (req.app.get('env') === 'development' ? err : {});
58 // render the error page
59 res.status(err.status || 500);
60 res.send(`
61 <!doctype html>
62 <h1>= message</h1>
63 <h2>= error.status</h2>
64 <pre>#{error.stack}</pre>
65 `);
66});
67
68module.exports = app;