app.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. res.header("Access-Control-Allow-Origin", req.headers.Origin || req.headers.origin || 'https://cangdu.org');
  17. res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
  18. res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  19. res.header("Access-Control-Allow-Credentials", true); //可以带cookies
  20. res.header("X-Powered-By", 'Express');
  21. if (req.method == 'OPTIONS') {
  22. res.sendStatus(200);
  23. } else {
  24. next();
  25. }
  26. });
  27. // app.use(Statistic.apiRecord)
  28. const MongoStore = connectMongo(session);
  29. app.use(cookieParser());
  30. app.use(session({
  31. name: config.session.name,
  32. secret: config.session.secret,
  33. resave: true,
  34. saveUninitialized: false,
  35. cookie: config.session.cookie,
  36. store: new MongoStore({
  37. url: config.url
  38. })
  39. }))
  40. // app.use(expressWinston.logger({
  41. // transports: [
  42. // new (winston.transports.Console)({
  43. // json: true,
  44. // colorize: true
  45. // }),
  46. // new winston.transports.File({
  47. // filename: 'logs/success.log'
  48. // })
  49. // ]
  50. // }));
  51. router(app);
  52. // app.use(expressWinston.errorLogger({
  53. // transports: [
  54. // new winston.transports.Console({
  55. // json: true,
  56. // colorize: true
  57. // }),
  58. // new winston.transports.File({
  59. // filename: 'logs/error.log'
  60. // })
  61. // ]
  62. // }));
  63. app.use(history());
  64. app.use(express.static('./public'));
  65. app.listen(config.port, () => {
  66. console.log(
  67. chalk.green(`成功监听端口:${config.port}`)
  68. )
  69. });