app.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 indexRouter = require('./routes/index');
  7. var postRouter = require('./routes/post');
  8. var configRouter = require('./routes/config');
  9. var nunjucks = require('nunjucks');
  10. require('dotenv').config();
  11. var app = express();
  12. app.use(logger('dev'));
  13. app.use(express.json());
  14. app.use(express.urlencoded({ extended: true, type: 'application/x-www-form-urlencoded' }));
  15. app.use(cookieParser());
  16. app.use(express.static(path.join(__dirname, 'public')));
  17. const viewEnv = nunjucks.configure('views', {
  18. autoescape: true,
  19. express: app
  20. });
  21. const languages = process.env.LANGUAGES
  22. .split(',')
  23. .map(language => {
  24. const l = language.split(':')
  25. return {
  26. "code": l[0],
  27. "name": l[1]
  28. }
  29. }
  30. )
  31. //nunjucks.addFilter
  32. viewEnv.addGlobal('languages', languages);
  33. app.set('view engine', 'html');
  34. // Routes
  35. app.use('/', indexRouter);
  36. app.use('/posts?', postRouter);
  37. app.use('/config', configRouter);
  38. // catch 404 and forward to error handler
  39. app.use(function(req, res, next) {
  40. next(createError(404));
  41. });
  42. // error handler
  43. app.use(function(err, req, res, next) {
  44. // set locals, only providing error in development
  45. res.locals.message = err.message;
  46. res.locals.error = req.app.get('env') === 'development' ? err : {};
  47. // render the error page
  48. res.status(err.status || 500);
  49. res.render('error.njk', {'res': res, 'err': err});
  50. });
  51. module.exports = app;