Node慕课网学习笔记(四)

3. Koa2 处理 http 请求

  1. 返回字符串格式:

ctx 即 res 和 req 的集合

const router = require('koa-router')()

router.prefix('/api')   // 前缀

// 定义路由:模拟获取留言板列表
router.get('/list', async (ctx) => {
  const query = ctx.query   // req 功能
  console.log('query', query)
  ctx.body = 'api list'   // res 功能(返回字符串格式)
})

// 定义路由:模拟创建留言内容
router.post('/create', async (ctx) => {
  const body = ctx.request.body  // request body
  console.log('body', body)
  ctx.body = 'api create'
})

module.exports = router // 输出
  • get 请求

    输入 http://localhost:3000/api/list?a=100&b=200

    控制台返回: { a: ‘100’, b: ‘200’ }

  • post 请求

    postman 中输入 http://localhost:3000/api/create

    body raw 下输入{ “content”: “新留言的内容”,“user”: “zhangsan”} //JSON

    send 后:控制台返回 { “content”: “新留言的内容”,“user”: “zhangsan”}

  1. 返回 JSON 格式

    ctx.body = {
    	errno: 0,
    	data: [
    		{ content: '留言1', user: '张三' },
    		{ content: '留言2', user: '李四' },
    		{ content: '留言3', user: '王二' },
    	]
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值