body-parser处理application/x-www-urlencoded参数解析错误踩坑

/post/body-parser article cover image

在使用application/x-www-urlencoded方式请求时,当传入的参数为数组集合类型时,会被body-parser错误解析需要通过设置urlencoded > extended为false

参考资料

sh
# 正确发送的FormData格式
list[0].xxx=1
list[1].xxx=2

# urlencoded后
list[0].xxx=1&list[1].xxx=2

错误解析

boday-parser-before

js
// 传入的数据格式
const list = [{ aaa: 1, bbb: 2 }];

request({ list }).then(res => {
  // ...
})

nodejs中间件配置:

js
const app = express();
const bodyParser = require('body-parser');

// 必须放置其他bodayParser之前否则无效
app.use(bodyParser.urlencoded({ extend: false }));
app.use(bodyParser.json());
app.use(xxx);

正确解析

boday-parser-after