Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

请问post handle时 如何通过ctx取得post body #157

Closed
hcwhan opened this issue Nov 25, 2019 · 5 comments
Closed

请问post handle时 如何通过ctx取得post body #157

hcwhan opened this issue Nov 25, 2019 · 5 comments
Assignees
Labels
enhancement New feature or request

Comments

@hcwhan
Copy link

hcwhan commented Nov 25, 2019

post('/XXXX').to.handle((ctx) => {
    console.log('ctx', ctx.request.body);
    ctx.type = 'html';
    ctx.body = '<body>Hello World</body>';
});

ctx.request.body 为空

@hcwhan hcwhan added the bug Something isn't working label Nov 25, 2019
@leeluolee leeluolee added enhancement New feature or request and removed bug Something isn't working labels Nov 25, 2019
@leeluolee
Copy link
Contributor

leeluolee commented Nov 25, 2019

临时解决方案

npm i koa-bodyparser

由于被限制直接require,但实际上可以引用相对路径。

const bodyParser = require('./node_modules/koa-bodyparser'); //relative path 

// bodyparser wrap
post('/XXXX').to.handle(bodyParser()).handle((ctx) => {
  console.log('ctx', ctx.request.body);
  ctx.type = 'html';
  ctx.body = ctx.request.body;
});

长期解决方案请关注这个issue, 因为 并非所有请求都应该默认parse body,因为考虑到代理等情况 ,我们需要评估下,但至少会提供一个 body-parser 插件出来, 避免上述又黑又脏的操作。比如

post('/XXXX').to.bodyParser().handle(...)

@xuchaoying
Copy link
Member

似乎更应该提供一个 action 供用户方便引入任意 koa middleware :

const bodyParser = require('koa-bodyparser');

post('/XXXX').to.middleware(bodyParser).handle((ctx) => {
  console.log('ctx', ctx.request.body);
  ctx.type = 'html';
  ctx.body = ctx.request.body;
});

@leeluolee
Copy link
Contributor

leeluolee commented Nov 26, 2019

@xuchaoying handle 貌似 就可以认为 use middleware ,只是它前置了 流量筛选操作 比如 getpost等,理论上也很方便前置统一处理,而无需每条route都声明,比如你可以

post('/(.*)').to.handle(bodyParser()); //后续所有post 操作都做bodyParser过滤
post('/XXXX').to.handle( ctx => {
  ctx.body = ctx.request.body;
});

@xuchaoying
Copy link
Member

恩恩,我意思是需要处理用户等第三方middleware引入的便捷性问题,而不是直接提供bodyParser这样的action

@svrxjs svrxjs deleted a comment from lyw9523132 Nov 27, 2019
@xuchaoying
Copy link
Member

v1.1.5 版本可以支持在 route 文件中引入 koa 中间件了。

const bodyParser = require('koa-bodyparser');

post('/test/post').to.handle(bodyParser()).handle((ctx) => {
  ctx.type = 'html';
  ctx.body = ctx.request.body;
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants