middleware.js

  1. const Koa = require("koa");
  2. const app = new Koa();
  3. const middleware = function async(ctx, next) {
  4. console.log(`this is a middleware!`);
  5. console.log(ctx.request.path);
  6. // next();
  7. };
  8. const middleware1 = function async(ctx, next) {
  9. console.log(`this is a middleware1!`);
  10. console.log(ctx.request.path);
  11. next();
  12. console.log(`this is a middleware1 ending!`);
  13. };
  14. const middleware2 = function async(ctx, next) {
  15. console.log(`this is a middleware2!`);
  16. console.log(ctx.request.path);
  17. next();
  18. console.log(`this is a middleware2 ending!`);
  19. };
  20. app.use(middleware1);
  21. app.use(middleware2);
  22. app.use(middleware);
  23. app.listen(3000);

index.js

  1. const Koa = require("koa");
  2. const Router = require("koa-router");
  3. const cors = require("@koa/cors");
  4. const koaBody = require("koa-body");
  5. const json = require("koa-json");
  6. const app = new Koa();
  7. const router = new Router();
  8. router.prefix("/api");
  9. router.get("/", (ctx) => {
  10. console.log(ctx);
  11. console.log(ctx.request);
  12. ctx.body = "hello koa";
  13. });
  14. router.get("/api", (ctx) => {
  15. // console.log(ctx);
  16. // console.log(ctx.request);
  17. const params = ctx.request.query;
  18. console.log(params);
  19. // ctx.body = "hello Api";
  20. ctx.body = {
  21. name: params.name,
  22. age: params.age,
  23. };
  24. });
  25. router.get("/async", async (ctx) => {
  26. ctx.body = await new Promise((resolve) => {
  27. setTimeout(() => {
  28. resolve("hello async 2s later");
  29. }, 2000);
  30. });
  31. });
  32. router.post("/post", async (ctx) => {
  33. let { body } = ctx.request;
  34. console.log(body);
  35. console.log(ctx.request);
  36. ctx.body = {
  37. ...body,
  38. };
  39. });
  40. app.use(koaBody());
  41. app.use(cors());
  42. app.use(json({ pretty: false, param: "pretty" }));
  43. // request, method, respond
  44. // api url function router
  45. // ctx, async
  46. app.use(router.routes()).use(router.allowedMethods());
  47. app.listen(3000);

package.json

  1. {
  2. "name": "resource",
  3. "version": "1.0.0",
  4. "description": "",
  5. "main": "index.js",
  6. "scripts": {
  7. "build": "webpack"
  8. },
  9. "keywords": [],
  10. "author": "",
  11. "license": "ISC",
  12. "dependencies": {
  13. "@koa/cors": "^3.1.0",
  14. "koa": "^2.13.0",
  15. "koa-body": "^4.2.0",
  16. "koa-router": "^9.4.0"
  17. },
  18. "devDependencies": {
  19. "koa-json": "^2.0.2"
  20. }
  21. }