一个小坑
npm i koa-bodyparser@2 -Snpm i @types/koa-bodyparser -Dimport * as Koa from 'koa';
import * as OtherParser from 'koa-better-body';
import * as bodyParser from 'koa-bodyparser';
import * as Router from 'koa-better-router';
import * as Convert from 'koa-convert';
const router = Router().loadMethods();
const app = new Koa();
router.get('/hello', async (ctx, next) => {
console.log(ctx.request.body);
ctx.body = `Hello world! Prefix: ${ctx.route.prefix}`
await next()
});
router.post('/upload/:id', async (ctx, next) => {
console.log(ctx.request.files)
console.log(ctx.request.fields)
// there's no `.body` when `multipart`,
// `urlencoded` or `json` request
console.log(ctx.request.body);
// print it to the API requester
ctx.body = JSON.stringify({
fields: ctx.request.fields,
files: ctx.request.files,
body: ctx.request.body || null
}, null, 2)
await next();
})
router.get('/foobar', async (ctx, next) => {
ctx.body = `Foo Bar Baz! ${ctx.route.prefix}`
await next()
})
const api = Router({ prefix: '/api' })
api.extend(router)
app.use(Convert(bodyParser()));
app.use(Convert(OtherParser()));
app.use(router.middleware());
app.use(api.middleware());
app.listen(3000, () => {
console.log("Server Stared on http://localhost:3000")
});Last updated