Remove test instructions, fix CORS for DELETE method
[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 var params = require('./config/parameters');
8
9 var 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 app.use(express.static(path.join(__dirname, 'static'))); //client "prod" files
32
33 // In development stage the client side has its own server
34 if (params.cors.enable)
35 {
36 app.use(function(req, res, next) {
37 res.header("Access-Control-Allow-Origin", params.cors.allowedOrigin);
38 res.header("Access-Control-Allow-Headers",
39 "Origin, X-Requested-With, Content-Type, Accept");
40 res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
41 next();
42 });
43 }
44
45 // Routing (AJAX-only)
46 const routes = require(path.join(__dirname, "routes", "all"));
47 app.use('/', routes);
48
49 // catch 404 and forward to error handler
50 app.use(function(req, res, next) {
51 next(createError(404));
52 });
53
54 // error handler
55 app.use(function(err, req, res, next) {
56 // set locals, only providing error in development
57 res.locals.message = err.message;
58 res.locals.error = (req.app.get('env') === 'development' ? err : {});
59 // render the error page
60 res.status(err.status || 500);
61 res.send(`
62 <!doctype html>
63 <h1>= message</h1>
64 <h2>= error.status</h2>
65 <pre>#{error.stack}</pre>
66 `);
67 });
68
69 module.exports = app;