server.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import Koa from 'koa'
  2. import http from 'http'
  3. import convert from 'koa-convert'
  4. import logger from 'koa-logger'
  5. import cors from 'koa-cors' // 跨域
  6. import bodyParser from 'koa-bodyparser' // 请求体JSON解析
  7. import onerror from 'koa-onerror' // 错误处理
  8. import resource from 'koa-static' // 静态资源托管
  9. import path, { dirname } from 'path'
  10. import routes from './routes/index.js'
  11. import config from '../config/config.js'
  12. import { fileURLToPath } from 'url'
  13. const __filename = fileURLToPath(import.meta.url)
  14. const __dirname = dirname(__filename)
  15. const app = new Koa()
  16. onerror(app)
  17. app.use(cors())
  18. app.use(convert(logger()))
  19. app.use(bodyParser())
  20. app.use(resource(path.join(__dirname, '../public')))
  21. // app.use(json({ pretty: false, param: 'pretty' }))
  22. app.use(async (ctx, next) => {
  23. const start = new Date()
  24. await next()
  25. const ms = new Date() - start
  26. console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
  27. })
  28. // routes
  29. app.use(routes.routes(), routes.allowedMethods())
  30. app.on('error', (error, ctx) => {
  31. console.log('奇怪的错误' + JSON.stringify(ctx.onerror))
  32. console.log('server error:' + error)
  33. })
  34. http.createServer(app.callback()).listen(config.port).on('listening', function () {
  35. console.log('正在监听端口' + config.port)
  36. })
  37. export default app