Node.js无法获取表单数据并保存至MongoDB的问题求助
问题:POST表单数据无法正确保存到MongoDB
尝试将POST表单的请求体数据保存到MongoDB中,但每次仅得到如下结果:
{ _id: new ObjectId("63f222995b85f79e258642c4"), __v: 0 }
期望的正确结果应为:
{ _id: new ObjectId("63f222995b85f79e258642c4"), username:"xyz",password:"xyz",__v: 0 }
提供的代码
HTML表单代码
<form action="/" method="post"> <div class="item11 bg12"> <input id="inph" type="text" class="in bg1" placeholder="Phone number, username or email address"> </div> <div class="item11"> <input id="inpass" type="text" class="in bg1" placeholder="password"> </div> <div class="item11"> <button type="submit" id="btlog" class="in bg2">Log in</button> </div> </form>
Node.js代码
Mongoose模型定义
const credential=mongoose.Schema({username:String,password:String});const cr_den=mongoose.model('instagram_clone',credential);
路由处理
app.get('/',(req,res)=>{res.render('index.pug');})
app.post('/',(req,res)=>{var data=new cr_den(req.body);data.save().then(()=>{console.log("response Noted..!!");console.log(data);}).catch(()=>{console.log('Failed To Save Data...!!!')})res.render('index.pug');})
问题原因及修复方法
1. 表单输入缺少name属性
HTML表单的输入框仅设置了id,但表单提交时,只有带name属性的输入值才会被打包到请求体中,导致后端req.body中没有username和password字段,自然无法存入MongoDB。
修改后的输入框代码:
<input id="inph" type="text" name="username" class="in bg1" placeholder="Phone number, username or email address"> <input id="inpass" type="password" name="password" class="in bg1" placeholder="password">
提示:密码输入建议使用type="password",避免明文显示。
2. 配置Express请求体解析中间件
Express默认不解析POST表单的请求体,需要添加express.urlencoded()中间件来解析application/x-www-form-urlencoded类型的请求数据。
在你的Express应用初始化代码中添加:
app.use(express.urlencoded({ extended: true }));
3. 调试请求体与错误信息
在POST路由中先打印req.body确认数据是否正确接收,同时在catch中打印错误详情,便于排查问题:
app.post('/',(req,res)=>{ console.log('Received request body:', req.body); var data=new cr_den(req.body); data.save().then(()=>{ console.log("response Noted..!!"); console.log(data); }).catch((err)=>{ console.log('Failed To Save Data...!!!', err); }) res.render('index.pug'); })
内容的提问来源于stack exchange,提问作者Tejas Adhude
相关产品推荐
相关产品推荐

