app.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import express from 'express';
  2. import db from './mongodb/db.js';
  3. import config from 'config-lite';
  4. import router from './routes/index.js';
  5. import cookieParser from 'cookie-parser'
  6. import session from 'express-session';
  7. import connectMongo from 'connect-mongo';
  8. import winston from 'winston';
  9. import expressWinston from 'express-winston';
  10. import path from 'path';
  11. import history from 'connect-history-api-fallback';
  12. import chalk from 'chalk';
  13. // import Statistic from './middlewares/statistic'
  14. const app = express();
  15. app.all('*', (req, res, next) => {
  16. const { origin, Origin, referer, Referer } = req.headers;
  17. const allowOrigin = origin || Origin || referer || Referer || '*';
  18. res.header("Access-Control-Allow-Origin", allowOrigin);
  19. res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
  20. res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  21. res.header("Access-Control-Allow-Credentials", true); //可以带cookies
  22. res.header("X-Powered-By", 'Express');
  23. if (req.method == 'OPTIONS') {
  24. res.sendStatus(200);
  25. } else {
  26. next();
  27. }
  28. });
  29. // app.use(Statistic.apiRecord)
  30. const MongoStore = connectMongo(session);
  31. app.use(cookieParser());
  32. app.use(session({
  33. name: config.session.name,
  34. secret: config.session.secret,
  35. resave: true,
  36. saveUninitialized: false,
  37. cookie: config.session.cookie,
  38. store: new MongoStore({
  39. url: config.url
  40. })
  41. }))
  42. // app.use(expressWinston.logger({
  43. // transports: [
  44. // new (winston.transports.Console)({
  45. // json: true,
  46. // colorize: true
  47. // }),
  48. // new winston.transports.File({
  49. // filename: 'logs/success.log'
  50. // })
  51. // ]
  52. // }));
  53. router(app);
  54. // app.use(expressWinston.errorLogger({
  55. // transports: [
  56. // new winston.transports.Console({
  57. // json: true,
  58. // colorize: true
  59. // }),
  60. // new winston.transports.File({
  61. // filename: 'logs/error.log'
  62. // })
  63. // ]
  64. // }));
  65. app.use(history());
  66. app.use(express.static('./public'));
  67. app.listen(config.port, () => {
  68. console.log(
  69. chalk.green(`成功监听端口:${config.port}`)
  70. )
  71. });