server app.ts

src/app.ts

  1. import Koa from 'koa'
  2. import cors from '@koa/cors'
  3. import logger from 'koa-logger'
  4. import bodyparser from 'koa-bodyparser'
  5. import jwt from 'koa-jwt'
  6. // routes
  7. import authRoutes from './routes/auth'
  8. import accessRoutes from './routes/access'
  9. import roleRoutes from './routes/roles'
  10. import roleAccessRoutes from './routes/roleAccess'
  11. import userRoutes from './routes/user'
  12. // secret
  13. import { jwtSecret } from './config/auth'
  14. // koa应用实例
  15. const app = new Koa()
  16. // middlewares
  17. app.use(cors()) // 支持跨域
  18. app.use(bodyparser({ // 解析请求体
  19. enableTypes: ['json', 'form', 'text']
  20. }))
  21. app.use(logger()) // 开发日志中间件
  22. // 自定义401错误
  23. app.use((ctx, next) => {
  24. return next().catch(err => {
  25. if (err.status === 401) {
  26. ctx.status = 401
  27. ctx.body = {
  28. code: 401,
  29. error: '未登录 token失效'
  30. }
  31. } else {
  32. ctx.throw(err)
  33. }
  34. })
  35. })
  36. // token验证 header未携带token 直接返回401 Authentication Error
  37. app.use(jwt(({ secret: jwtSecret })).unless({
  38. // 白名单
  39. path: ['/api/auth/login', '/api/auth/register']
  40. }))
  41. // routes
  42. // 用户验证路由(登录 注册)
  43. app.use(authRoutes.routes()).use(authRoutes.allowedMethods())
  44. app.use(accessRoutes.routes()).use(accessRoutes.allowedMethods())
  45. app.use(roleRoutes.routes()).use(roleRoutes.allowedMethods())
  46. app.use(roleAccessRoutes.routes()).use(roleAccessRoutes.allowedMethods())
  47. app.use(userRoutes.routes()).use(userRoutes.allowedMethods())
  48. // listen
  49. const port = process.env.PORT || '3003'
  50. app.listen(port, () => {
  51. console.log(`server listening on ${port}`)
  52. })
  53. app.on('error', (err) =>
  54. console.error('server error', err)
  55. )