-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.6.js
51 lines (39 loc) · 1.01 KB
/
index.6.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const Koa = require("koa");
const Router = require('koa-router');
const bodyparser = require('koa-bodyparser')
const app = new Koa();
const router = new Router();
const usersRouter = new Router({prefix:'/users'})
/**
* 增删改查
*/
router.get('/',ctx=>{
ctx.body = '这是主页'
})
const db = [{ name: "张三" }]
usersRouter.get('/',(ctx)=>{
// ctx.set('Allow','GET,POST')
ctx.body = db;
})
usersRouter.post('/',(ctx)=>{
console.log(ctx.request)
db.push(ctx.request.body)
ctx.body = ctx.request.body;
})
usersRouter.put('/:id',(ctx)=>{
db[ctx.params.id*1] = ctx.request.body;
ctx.body = ctx.request.body;
})
usersRouter.delete('/:id',(ctx)=>{
db.splice(ctx.params.id*1,1);
ctx.status = 204;
})
usersRouter.get('/:id',(ctx)=>{
ctx.body = db[Number(ctx.params.id)]
})
// 该中间件一定要在路由之前,不然ctx.request.body访问不到
app.use(bodyparser())
app.use(router.routes());
app.use(usersRouter.routes());
app.use(usersRouter.allowedMethods());
app.listen(3000);