server.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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, { dirname } from 'path'
  14. import routes from './routes/index.js'
  15. import config from '../config/config.js'
  16. import { fileURLToPath } from 'url'
  17. const __filename = fileURLToPath(import.meta.url)
  18. const __dirname = dirname(__filename)
  19. const app = new Koa()
  20. onerror(app)
  21. app.use(convert(cors()))
  22. app.use(convert(logger()))
  23. app.use(bodyParser())
  24. app.use(resource(path.join(__dirname, '../public')))
  25. // app.use(json({ pretty: false, param: 'pretty' }))
  26. app.use(async (ctx, next) => {
  27. const start = new Date()
  28. await next()
  29. const ms = new Date() - start
  30. console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
  31. })
  32. // routes
  33. app.use(routes.routes(), routes.allowedMethods())
  34. app.on('error', (error, ctx) => {
  35. console.log('奇怪的错误' + JSON.stringify(ctx.onerror))
  36. console.log('server error:' + error)
  37. })
  38. http.createServer(app.callback()).listen(config.port).on('listening', function () {
  39. console.log('正在监听端口' + config.port)
  40. })
  41. export default app