Advance on client side
[vchess.git] / server / app.js
1 var createError = require('http-errors');
2 var express = require('express');
3 var path = require('path');
4 var cookieParser = require('cookie-parser');
5 var logger = require('morgan');
6 var favicon = require('serve-favicon');
7
8 var app = express();
9
10 app.use(favicon(path.join(__dirname, "static", "favicon.ico")));
11
12 if (app.get('env') === 'development')
13 {
14 // Full logging in development mode
15 app.use(logger('dev'));
16 }
17 else
18 {
19 // http://dev.rdybarra.com/2016/06/23/Production-Logging-With-Morgan-In-Express/
20 app.set('trust proxy', true);
21 // In prod, only log error responses (https://github.com/expressjs/morgan)
22 app.use(logger('combined', {
23 skip: function (req, res) { return res.statusCode < 400 }
24 }));
25 }
26
27 app.use(express.json());
28 app.use(express.urlencoded({ extended: false }));
29 app.use(cookieParser());
30 app.use(express.static(path.join(__dirname, 'static'))); //client "prod" files
31
32 // In development stage the client side has its own server
33 if (params.cors.enable)
34 {
35 app.use(function(req, res, next) {
36 res.header("Access-Control-Allow-Origin", params.cors.allowedOrigin);
37 res.header("Access-Control-Allow-Headers",
38 "Origin, X-Requested-With, Content-Type, Accept");
39 next();
40 });
41 }
42
43 // Routing (AJAX-only)
44 const routes = require(path.join(__dirname, "routes", "all"));
45 app.use('/', routes);
46
47 // catch 404 and forward to error handler
48 app.use(function(req, res, next) {
49 next(createError(404));
50 });
51
52 // error handler
53 app.use(function(err, req, res, next) {
54 // set locals, only providing error in development
55 res.locals.message = err.message;
56 res.locals.error = (req.app.get('env') === 'development' ? err : {});
57 // render the error page
58 res.status(err.status || 500);
59 res.send(`
60 <!doctype html>
61 <h1>= message</h1>
62 <h2>= error.status</h2>
63 <pre>#{error.stack}</pre>
64 `);
65 });
66
67 module.exports = app;