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

提交HTML表单数据时无法创建campground对象的问题排查

问题排查:表单提交后req.body格式不符合预期

注:该问题已确认是Edge浏览器兼容性问题,保留供遇到同类情况的用户参考,建议使用Chrome测试。

用户尝试通过HTML表单提交包含title和location属性的campground对象,但返回的req.body格式与预期不符,具体情况如下:

提交表单代码

<form action="/campgrounds" method="POST">
    <div>
        <label for="title">Title</label><br>
        <input type="text" id="title" name="campground[title]">
    </div>
    <div>
        <label for="location">Location</label><br>
        <input type="text" id="location" name="campground[location]">
    </div>
    <button>Add Campground</button>
</form>

Express POST路由代码

app.post("/campgrounds",async(req,res)=>{
  res.send(req.body);
  // const campground=new Campground(req.body.campground)

  // await campground.save();

  // res.redirect(`/campgrounds/${campground._id}`)
})

预期与实际结果

预期req.body格式

{campground:{"title":"fdwdddsss","location":"ddhffwwscss"}}

实际返回格式

{
  "campground{title}": "fdwdddsss",
  "campground{location}": "ddhffwwscss"
}

错误原因

这是Edge浏览器的兼容性问题:Edge在处理表单字段名中的方括号[]时,错误地将其转换为大括号{},导致Express的body解析器无法识别嵌套对象的命名规则,最终生成了平面对象而非预期的嵌套结构。

解决方案

更换为Chrome浏览器进行测试,Chrome能正确解析表单字段名中的方括号,让body解析器正常生成嵌套的campground对象,匹配预期格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 04:20:30