app.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * Q&A
  3. * 如果导出或导入模块?
  4. * 因项目没有使用BABEL或者typescrip的转换工具,无法支持import/export的方式
  5. * import/export在ES7才得到支持,就算node7也无法使用
  6. * 所以我们使用module.exports来导出require来导入
  7. */
  8. var express = require('express')
  9. var path = require('path')
  10. var logger = require('morgan')
  11. var cookieParser = require('cookie-parser')
  12. var bodyParser = require('body-parser')
  13. var mongoose = require('mongoose')
  14. var ejs = require('ejs')
  15. var config = require('./config')
  16. var fileUpload = require('express-fileupload')
  17. mongoose.Promise = require('bluebird')
  18. mongoose.connect(config.mongo.uri, { user: config.mongo.user, pass: config.mongo.pass })
  19. mongoose.connection.on('error', function (err) {
  20. console.error(`MongoDB connection error: ${err}`)
  21. process.exit(-1);
  22. })
  23. var app = express()
  24. // view engine setup
  25. // app.set('views', path.join(__dirname, 'views'))
  26. // app.set('view engine', 'hbs'
  27. app.engine('.html', ejs.__express);
  28. app.set('view engine', 'html');
  29. app.set('views', path.join(__dirname, 'views'))
  30. app.all('*', function (req, res, next) {
  31. res.header('Access-Control-Allow-Origin', '*');
  32. res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With');
  33. res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  34. if (req.method === 'OPTIONS') {
  35. res.send(200); /让options请求快速返回/
  36. }
  37. else {
  38. next();
  39. }
  40. });
  41. // uncomment after placing your favicon in /public
  42. //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
  43. app.use(logger('dev'))
  44. app.use(bodyParser.json({ 'limit': '20000kb' }))
  45. app.use(bodyParser.urlencoded({ extended: false }))
  46. app.use(cookieParser())
  47. app.use(express.static(path.join(__dirname, 'public')))
  48. app.use(express.static(path.join(__dirname, 'webapp/dist')))
  49. app.use(fileUpload())
  50. require('./routers')(app)
  51. // error handler
  52. app.use(function (err, req, res, next) {
  53. // set locals, only providing error in development
  54. res.locals.message = err.message
  55. res.locals.error = req.app.get('env') === 'development' ? err : {}
  56. res.status(err.status || 500)
  57. res.send(err.message)
  58. });
  59. module.exports = app