koa2 如何获取参数?

环境 koa2 node7

// controllers/user.js
const user = require('../models/user');

const getUserInfo = async (ctx) => {
  const id = this.params['id'];
  this.body = await user.getUserById(id);
};

module.exports = {
  auth: (router) => {
    router.get('/user/:id', getUserInfo);
  }
};

断点调试可以查到 params的 id 参数
clipboard.png

但继续执行会报错,

clipboard.png

参考文章:学习的博客

补充:我不会用 Koa2 的 context。
下面是我打印 ctx 为一个 空数组

clipboard.png

终结:
感谢 @soonfy @鱼香肉丝盖饭 最终解决方案是再次看文档发现 如使用 async/await koa-router 需要 7.0.1

cnpm i koa-router@next --save
阅读 13.5k
2 个回答

ctx封装req和res,你需要的可能是req.params.id。

soonfy

是这样获取:

ctx.params.id
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题