server.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /////////////////MARK:必读////////////////
  2. //后来人,接受这个项目不要迷茫,不要彷徨
  3. //代码逻辑混乱,接口数据有问题,请你坚持下去
  4. //谨记,请勿辱骂前人
  5. import Koa from 'koa';
  6. import http from 'http'
  7. import convert from 'koa-convert'
  8. import logger from 'koa-logger'
  9. import cors from 'koa-cors' //跨域
  10. import bodyParser from 'koa-bodyparser' //请求体JSON解析
  11. import onerror from 'koa-onerror' //错误处理
  12. import resource from 'koa-static' //静态资源托管
  13. import path from 'path'
  14. import routes from './routes/index.js'
  15. import config from '../config/config.js'
  16. import { fileURLToPath } from 'url';
  17. import { dirname } from 'path';
  18. const __filename = fileURLToPath(import.meta.url);
  19. const __dirname = dirname(__filename);
  20. const app = new Koa();
  21. onerror(app)
  22. app.use(convert(cors()))
  23. app.use(convert(logger()))
  24. app.use(bodyParser())
  25. app.use(resource(path.join(__dirname, '../public')))
  26. // app.use(json({ pretty: false, param: 'pretty' }))
  27. app.use(async (ctx, next) => {
  28. const start = new Date()
  29. await next()
  30. const ms = new Date() - start
  31. console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
  32. })
  33. // routes
  34. app.use(routes.routes(), routes.allowedMethods());
  35. app.on('error', (error, ctx) => {
  36. console.log('奇怪的错误' + JSON.stringify(ctx.onerror))
  37. console.log('server error:' + error)
  38. })
  39. http.createServer(app.callback()).listen(config.port).on('listening', function () {
  40. console.log('正在监听端口' + config.port)
  41. })
  42. export default app;