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

如何使用Supertest发送同键多值的表单请求?

解决Supertest发送同键多值表单数据的问题

你遇到的问题根源是:JS对象中重复的键会被最后一个值覆盖,所以用{color: 'red', color: 'green', color: 'blue'}这种方式传参时,前面的值都会被blue覆盖。这里有两种可行的解决方法:

方法一:用数组作为键对应的值

Supertest依赖的superagent库支持直接传递数组,它会自动将数组转换为同键多值的表单格式:

await request(app)
  .post('/你的接口路径')
  .type('form')
  .send({ color: ['red', 'blue', 'green'] });

需要注意:确保你的Express项目中,urlencoded中间件配置了extended: true,这样才能正确解析数组类型的参数:

app.use(express.urlencoded({ extended: true }));

方法二:直接构造urlencoded格式的字符串

如果想完全模拟原生表单提交的原始格式,可以直接拼接成key=value的字符串发送:

await request(app)
  .post('/你的接口路径')
  .type('form')
  .send('color=red&color=blue&color=green');

这两种方法都能让Express的req.body.color接收到完整的数组['red', 'blue', 'green']。

内容的提问来源于stack exchange,提问作者Sebastian Hothaza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 13:02:39