12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- import Router from '@koa/router';
- import { koaBody } from 'koa-body';
- const router = new Router();
- // 定义一些静态数据
- const users = [
- {
- id: 1,
- name: '果果',
- age: 18,
- },
- {
- id: 2,
- name: '静静',
- age: 38,
- },
- {
- id: 3,
- name: '欣欣',
- age: 18,
- },
- {
- id: 4,
- name: '诗诗',
- age: 28,
- },
- ];
- let uid = 4; // 用来储存当前最新添加用户的id值
- router
- // 获取所有用户数据
- .get('/', (ctx) => {
- //! 如果响应数据类型 赋值为 一个对象,那么koa会自动设置响应头content-type = application/json;chartset=utf-8
- ctx.body = users;
- })
- // 分页获取数据
- // 思考:1 是get还是post;get 2 需要给服务端 传递数据吗? 当前页码current and 每页条数count
- .get('/page', (ctx) => {
- // ? 如何获取用户传递过来的参数current以及count?
- //! koa框架 会 自动处理所有请求的查询参数 -- 在处理路由时,可以直接通过ctx.query来获取所有的查询参数
- // ctx.query 获取所有转译后查询参数对象
- // console.log(ctx.query);
- const { current, count } = ctx.query;
- // 从总数据的数组中正确的截取出我们想要的那些数据
- // 1 用数组的slice方法 进行 数据截取
- // 1: [0,1) 2: [1, 2) 3: [2, 3)... m: [(m-1)*count, count * m )
- ctx.body = users.slice((current - 1) * count, current * count);
- })
- // 添加新用户
- .post('/insert', (ctx) => {
- // console.log(ctx.request.body);
- users.push({ ...ctx.request.body, id: ++uid });
- ctx.body = '添加成功';
- })
- // 上传文件
- .put(
- '/upload',
- koaBody({
- multipart: true,
- formidable: {
- uploadDir: './public',
- keepExtensions: true,
- },
- }),
- (ctx) => {
- // 获取待上传的文件
- console.log(ctx.request.files);
- ctx.body = `/${ctx.request.files.file.newFilename}`;
- }
- );
- export default router;
|