node.js - koa2 如何获取参数?
ringa_lee
ringa_lee 2017-04-17 16:18:20
0
2
760

环境 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 参数

但继续执行会报错,

参考文章:学习的博客

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

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

cnpm i koa-router@next --save
ringa_lee
ringa_lee

ringa_lee

모든 응답(2)
伊谢尔伦

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

soonfy

洪涛

是这样获取:

ctx.params.id
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!