index.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import Koa from 'koa';
  2. import { PORT, HOST } from './app.config.mjs';
  3. import router from './router/index.mjs';
  4. const app = new Koa();
  5. // 中间件的执行顺序
  6. // 通过app.use方法 去 使用中间件。多次调用 就可以 注册多个中间件
  7. // app.use((ctx, next) => {
  8. // console.log('a');
  9. // next();
  10. // });
  11. // app.use((ctx, next) => {
  12. // next();
  13. // console.log('b');
  14. // });
  15. // app.use((ctx, next) => {
  16. // console.log('c');
  17. // next();
  18. // });
  19. // app.use((ctx, next) => {
  20. // console.log('a start');
  21. // next();
  22. // console.log('a end');
  23. // });
  24. // app.use((ctx, next) => {
  25. // console.log('b start');
  26. // next();
  27. // console.log('b end');
  28. // });
  29. // app.use((ctx, next) => {
  30. // console.log('c start');
  31. // next();
  32. // console.log('c end');
  33. // });
  34. // a start, b start, c start, c end, b end, a end
  35. // app.use(async (ctx, next) => {
  36. // console.log('a start');
  37. // await next();
  38. // console.log('a end');
  39. // });
  40. // app.use(async (ctx, next) => {
  41. // console.log('b start');
  42. // await next();
  43. // console.log('b end');
  44. // });
  45. // app.use(async (ctx, next) => {
  46. // console.log('c start');
  47. // await next();
  48. // console.log('c end');
  49. // });
  50. // app.use((ctx) => {
  51. // ctx.body = 'hello, world.';
  52. // });
  53. //! 总结:中间件的执行顺序 遵循 洋葱模型
  54. // 注入路由功能
  55. app.use(router.routes());
  56. // 在options请求中响应服务端支持哪些跨域的请求方法
  57. app.use(router.allowedMethods());
  58. app.listen(PORT, HOST, () => {
  59. console.info(`Server is running at 'http://${HOST}:${PORT}'`);
  60. });