index.mjs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import Router from '@koa/router';
  2. import { koaBody } from 'koa-body';
  3. const router = new Router();
  4. // 定义一些静态数据
  5. const users = [
  6. {
  7. id: 1,
  8. name: '果果',
  9. age: 18,
  10. },
  11. {
  12. id: 2,
  13. name: '静静',
  14. age: 38,
  15. },
  16. {
  17. id: 3,
  18. name: '欣欣',
  19. age: 18,
  20. },
  21. {
  22. id: 4,
  23. name: '诗诗',
  24. age: 28,
  25. },
  26. ];
  27. let uid = 4; // 用来储存当前最新添加用户的id值
  28. router
  29. // 获取所有用户数据
  30. .get('/', (ctx) => {
  31. //! 如果响应数据类型 赋值为 一个对象,那么koa会自动设置响应头content-type = application/json;chartset=utf-8
  32. ctx.body = users;
  33. })
  34. // 分页获取数据
  35. // 思考:1 是get还是post;get 2 需要给服务端 传递数据吗? 当前页码current and 每页条数count
  36. .get('/page', (ctx) => {
  37. // ? 如何获取用户传递过来的参数current以及count?
  38. //! koa框架 会 自动处理所有请求的查询参数 -- 在处理路由时,可以直接通过ctx.query来获取所有的查询参数
  39. // ctx.query 获取所有转译后查询参数对象
  40. // console.log(ctx.query);
  41. const { current, count } = ctx.query;
  42. // 从总数据的数组中正确的截取出我们想要的那些数据
  43. // 1 用数组的slice方法 进行 数据截取
  44. // 1: [0,1) 2: [1, 2) 3: [2, 3)... m: [(m-1)*count, count * m )
  45. ctx.body = users.slice((current - 1) * count, current * count);
  46. })
  47. // 添加新用户
  48. .post('/insert', (ctx) => {
  49. // console.log(ctx.request.body);
  50. users.push({ ...ctx.request.body, id: ++uid });
  51. ctx.body = '添加成功';
  52. })
  53. // 上传文件
  54. .put(
  55. '/upload',
  56. koaBody({
  57. multipart: true,
  58. formidable: {
  59. uploadDir: './public',
  60. keepExtensions: true,
  61. },
  62. }),
  63. (ctx) => {
  64. // 获取待上传的文件
  65. console.log(ctx.request.files);
  66. ctx.body = `/${ctx.request.files.file.newFilename}`;
  67. }
  68. );
  69. export default router;