opensource
opensource copied to clipboard
update docs for koa-better-body
- switch example to use https://github.com/tunnckoCore/koa-better-router
- add table of contents
Would appreciate you doing this. I have a hard time figuring out how to use this with the router. All my routes 404 as soon as I use
the body parser.
what this
and which router? the current is using koa-router which support multiple mmiddlewares on one route, koa better router support that too
I was referring to this issue's title, updating the docs and switching the example to use koa-better-router.
I will post an example in a few minutes.
cool, thanks. in the koa better router have a workinkg example. pr is welcome too
server.js:
const Koa = require('koa');
const app = new Koa();
app.experimental = true
…
api
.resource('customer', require('./resources/customers'))
app.use(api.middleware());
customers.js:
const body = require('koa-better-body');
module.exports = {
index: async (ctx, next) => {
…
},
create: [body, async (ctx, next) => {
ctx.body = 'Foobar';
await next();
}]
}
As soon as I add [body
here, I receive a 404 from the backend on a POST to this resource. Without the body, it works fine.
you should invoke it, body(opts). dont know why users dont understand that. only when invoke it, it returns a middleware function. that can be passed to .use method and respectively as item in array passed to route.
I inspired myself from this example: https://github.com/tunnckoCore/koa-rest-router#createresource It doesn't invoke the module, it only passes it as the first element in the array of route handlers, just as I did above.
So should it be like this?
create: [body(), async (ctx, next) => {
ctx.body = 'Foobar';
await next();
}]
respectively:
const body = require('koa-better-body')()
create: [body, async (ctx, next) => {
…
Yep. Huh, good catch, it is wrong in that exact example, yea.
Thank you for the update!
I'm going to finish this issue too :) and maybe will patch the tunnckoCore/koa-better-body#77
I got 404 too, using Koa 2.2.0 and koa-router 7.1.1.
router.post("/", body(), async (ctx, next) => {
ctx.response.type = "json";
ctx.response.body = ctx.request.files;
});
With koa-convert, I got nothing in the request:
{ method: 'POST',
url: '/',
header:
{ host: 'localhost:3000',
connection: 'keep-alive',
'content-length': '21',
'postman-token': '7fb5a292-7e75-e57c-82db-8343c18e05ff',
'cache-control': 'no-cache',
origin: 'chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop',
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36',
'content-type': 'application/x-www-form-urlencoded',
accept: '*/*',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-US,en;q=0.8,id;q=0.6' } }
If this isn't compatible with koa-router, I think the README should state it.