You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用routing-controllers的Express应用接收合法JSON时为何返回400错误?

问题描述

我用routing-controllers搭建了一个Express应用,仅包含一个AuthController,代码如下:

@JsonController('/auth')
export class AuthController {
    public authService = new AuthService();

    @HttpCode(201)
    @Post('/signup')
    async signUp(@Body() data: SignUpDto) {
        return await this.authService.signup(data);
    }
}

对应的SignUpDto未设置任何校验规则:

export class SignUpDto {
    userId: string;
    email: string;
    password: string;
}

但通过cURL发送请求时:

curl --cacert ./.cert/cert.pem -X POST https://localhost/auth/signup -H 'Content-ype: application/json' -d '{"userId":"01GKYW1JQBCJBXAK0VJTX92C6E","email":"01GKYSZ8AHSE@gmail.com","password":"A1@2e3r4"}'

却收到400 Bad Request响应:

{"name":"BadRequestError","message":"Invalid body, check 'errors' property for more info.","stack":"Error\nat new HttpError (/home/user/Work/service/node_modules/routing-controllers/cjs/http-error/HttpError.js:17:22)\nat new BadRequestError (/home/user/Work/service/node_modules/routing-controllers/cjs/http-error/BadRequestError.js:10:9)\nat /home/user/Work/service/node_modules/routing-controllers/cjs/ActionParameterHandler.js:219:31\nat processTicksAndRejections (node:internal/process/task_queues:96:5)\nat async ActionParameterHandler.normalizeParamValue (/home/user/Work/service/node_modules/routing-controllers/cjs/ActionParameterHandler.js:134:21)\nat async Promise.all (index 0)","errors":[{"target":{"{\"userId\":\"01GKYW1JQBCJBXAK0VJTX92C6E\",\"email\":\"01GKYSZ8AHSE@gmail.com\",\"password\":\"A1@2e3r4\"}":""},"children":[],"constraints":{"unknownValue":"an unknown value was passed to the validate function"}}]}

卡在此问题数小时,求指点可能的原因。


可能的原因及解决办法
  • 请求头拼写错误:你curl命令里的Content-ype少了一个t,正确应该是Content-Type。这个错误会导致Express无法正确解析JSON请求体,routing-controllers拿到的是原始字符串而非解析后的对象,从而触发unknownValue校验错误。修正请求头后再测试。
  • DTO类缺失元数据标识:routing-controllers依赖类的元数据来识别DTO,哪怕没有校验规则,也需要给SignUpDto添加装饰器。可以尝试给SignUpDto加上@ClassSerializer()(来自class-transformer),或者确保项目中已正确配置class-transformer,让框架能识别这是一个需要转换的DTO类。
  • class-transformer/class-validator未正确配置:routing-controllers默认用这两个库处理请求体转换和校验。如果没安装这两个依赖,或者在routing-controllers的初始化配置里没开启transform: true,会导致无法将JSON对象转换为SignUpDto实例。检查依赖是否安装,配置是否正确。
  • JSON解析中间件问题:确认Express应用中已经添加了express.json()中间件。虽然routing-controllers可能自动添加,但如果手动调整过中间件顺序,可能导致请求体未被提前解析,框架拿到原始数据引发错误。

内容的提问来源于stack exchange,提问作者Edy Bourne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 14:20:26