美文网首页
koa-router 处理get/post

koa-router 处理get/post

作者: dsying | 来源:发表于2018-12-13 17:40 被阅读0次

目录结构


image.png
const Koa = require('koa')
// 注意require('koa-router')返回的是函数:
const router = require('koa-router')()
// 解析request的body的功能(post请求)
const bodyParser = require('koa-bodyparser');
// 处理静态文件
const serve = require("koa-static");


const app = new Koa()

app.use(async (ctx, next) => {
  console.log(`${ctx.method}`,`${ctx.url}`);
  await next()
  console.log(`1`);
})

// 添加 url映射(:hello URL命名参数 )
router.get('/:hello/:name', async (ctx, next) => {
  const { hello, name } = ctx.params
  ctx.body = `<h1>${hello}, ${name}</h1>`
})

router.get('/', async (ctx, next) => {
  ctx.body = `<h1>Index</h1>`
})

router.post('/postRoute', async (ctx, next) => {
  const rb = ctx.request.body
  console.log(rb);
  ctx.response.body = 'success'
})

//__dirname+ “/static/html” 表示静态文件存放的路径,
//当接收到请求后,会在该路径下进行查找,serve还可以接收一个对象,表示查找文件的后缀名
app.use(serve(__dirname+ "/static/html",{ extensions: ['html']}));
//由于middleware的顺序很重要,这个koa-bodyparser必须在router之前被注册到app对象上
app.use(bodyParser());
app.use(router.routes())

app.listen(3000)

相关文章

网友评论

      本文标题:koa-router 处理get/post

      本文链接:https://www.haomeiwen.com/subject/rhmbhqtx.html