midwayjs / midway

🍔 A Node.js Serverless Framework for front-end/full-stack developers. Build the application for next decade. Works on AWS, Alibaba Cloud, Tencent Cloud and traditional VM/Container. Super easy integrate with React and Vue. 🌈
https://www.midwayjs.org/
MIT License
7.34k stars 573 forks source link

使用 koa 作为 Web 框架时 @Body 数据为 undefined #834

Closed xuxucode closed 3 years ago

xuxucode commented 3 years ago

1. 初始化项目:mw new hello_koa --template=@midwayjs-examples/applicaiton-koa,并添加 Post 方法:

// hello_koa/src/controller/home.ts
import { ALL, Body, Controller, Post, Provide } from '@midwayjs/decorator';
import { User } from '../interface';

@Provide()
@Controller('/api/user')
export class HomeController {

  @Post('/')
  async updateUser(@Body(ALL) user: User ) {
    console.log('=== user: ', user); // user 为 undefined
    return {
      user,
    }
  }
}

2. 前端发送 POST 请求:

POST http://localhost:7001/api/user HTTP/1.1
content-type: application/json

{
  "id": 1,
  "name": "aaa"
}

3. 结果:获取不到 @Body 的 user 数据

但使用 Egg.js 作为 Web 框架时可以获取到 body 数据

czy88840616 commented 3 years ago

恩,设计是这样的,koa 的用户一般是希望最少最精简的功能,我们默认只包含了 koa-router,没有给用户提供 koa-body/koa-bodyparser,作为弥补,我刚在脚手架中增加一个默认的 bodyparser 作为示例。

代码如下:

// configuration.ts
import { Configuration, App, Config } from '@midwayjs/decorator';
import { ILifeCycle } from '@midwayjs/core';
import { Application } from '@midwayjs/koa';
import * as bodyParser from 'koa-bodyparser';

@Configuration()
export class ContainerLifeCycle implements ILifeCycle {
  @App()
  app: Application;

  async onReady() {
    this.app.use(bodyParser());
  }
}
// package.json
  "dependencies": {
    "@midwayjs/bootstrap": "^2.3.0",
    "@midwayjs/decorator": "^2.3.0",
    "@midwayjs/koa": "^2.3.0",
    "koa-bodyparser": "^4.3.0"
  },
xuxucode commented 3 years ago

能否考虑下把 bodyparser 作为 @midwayjs/koa 的默认中间件,这样 midway 在不同 web 框架上会有更大程度的一致性。Web 框能够处理 json 的话能方便绝大多数场景。

czy88840616 commented 3 years ago

这个我们考虑过,但是细想下去,会有些问题,目前没有加入一些默认的中间件,有一些原因:

在这些情况下,如果使用 koa 框架,那么可以完全的自定义,去创造一个属于自己的上层框架,比如给团队定制。

有两种方法:

不知道这样是否能理解。

xuxucode commented 3 years ago

解释得通,理解了。

czy88840616 commented 3 years ago

@xuxucode 感谢理解 Thanks♪(・ω・)ノ

waitingsong commented 3 years ago

就是方向性选择吧: 要么使用较为大而全、开箱即用的 egg,要么自己根据需求以 koa 为基础做定制开发。 egg 也是以 koa 为基础,如果把 koa 的也添加很多功能,就和 egg 没啥区别。

czy88840616 commented 3 years ago

恩,是的,midway 只是将所有框架,加上 ts、依赖注入、装饰器写法的能力,尽可能不对上层框架做过度的封装、选型。