一个小坑

优质
小牛编辑
125浏览
2023-12-01

koa-better-body 在新版本中并不提供body解析功能

新版本仅仅只提供文件,表单,或者Ajax JSON的请求解析,而且从 koa-better-router 的不支持参数匹配来看,这2个插件配合起来更适合做 restful api 。假如我们要解析url上面的参数,所以我们还需要自己再弄一个body解析的插件。

npm i koa-bodyparser@2 -S
npm i @types/koa-bodyparser -D

再次修改我们的 index.ts,这里我们选择老的版本是因为我当前的node是6.9,而且typescript并不支持将引入的模块也进行编译降级处理,除非我们用webpack或者其他的打包工具,这里为了简单就直接使用老一点的版本。

import * 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")
});

当然我们后面可能并不会用到 body,这里仅仅只是把这个坑提一下,其实我们手动解析一下也非常简单,使用 ctx.querystring,通过 split 就可以直接拿到。

let str = 'a=2&b=3'

let arr = str.split('&')

arr.reduce((prev,i) => (prev[i.split('=')[0]] = i.split('=')[1], prev),{})

// { a: 2, b: 3}