server.js 1.3 KB

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