const Koa = require('koa')
const router = require('koa-router')()
const views = require('koa-views')
const nunjucks = require('nunjucks')
const session = require('koa-session')
const parser = require('koa-parser')
const app = new Koa()
app.keys = ['123456']
app.use(parser())
app.use(
session(
{
maxAge: 10 * 1000
},
app
)
)
app.use(
views(__dirname + '/views', {
map: { html: 'nunjucks' }
})
)
let dataList = ['水果', '苹果', '菠萝']
router.get('/fruits', ctx => {
ctx.body = dataList
})
router.post('/fruits', ctx => {
let fruit = ctx.request.body.fruit
console.log(fruit)
dataList.push(fruit)
ctx.body = dataList
})
router.put('/fruits/:id', ctx => {
let id = ctx.params.id
console.log(id)
let fruit = ctx.request.body.fruit
console.log(fruit)
dataList.splice(id, 1, fruit)
ctx.body = dataList
})
router.delete('/fruits/:id', ctx => {
let id = ctx.params.id
dataList.splice(id, 1)
ctx.body = dataList
})
app.use(router.routes())
app.listen(3001, () => {
console.log('server is running')
})