POST请求报错TypeError: Cannot read properties of undefined (reading 'username')且无法完成更新求助
POST请求报错TypeError: Cannot read properties of undefined (reading 'username')且无法完成更新求助
兄弟,我一看这个报错就知道问题所在啦!你遇到的TypeError: Cannot read properties of undefined (reading 'username'),核心原因是**req.body是undefined**——也就是说你的Express应用根本没解析POST请求里的表单/JSON数据,自然读不到username属性。
给你一步步解决的方案:
首先必须添加请求体解析中间件
Express默认不会自动解析POST请求的请求体,所以你得在路由配置之前,加上这两行中间件代码:// 解析表单格式的请求体(application/x-www-form-urlencoded) app.use(express.urlencoded({ extended: true })); // 解析JSON格式的请求体(如果前端用axios/fetch发JSON的话需要) app.use(express.json());注意!这两行一定要放在你的
app.post('/create-user', ...)路由代码之前,不然中间件不会生效哦。先验证中间件是否生效
你可以在路由里先打印req.body,确认它不再是undefined:app.post('/create-user', function(req, resp) { console.log('请求体内容:', req.body); // 看控制台输出,正常的话会有username和password // 后续的MongoDB操作代码... });顺便优化你的MongoDB连接逻辑
你现在的代码里没写client.connect(),这会导致数据库连接失败哦,建议改成异步写法更稳妥:app.post('/create-user', async function(req, resp) { let client; try { client = new MongoClient(uri); await client.connect(); // 必须先建立数据库连接 const dbo = client.db("eggyDB"); const collName = dbo.collection("users"); const info = { username: req.body.username, password: req.body.password }; await collName.insertOne(info); console.log('User created'); resp.render("main", { layout: "homepage", title: "My Home page" }); } catch(err) { console.error('Error creating user:', err); resp.status(500).send('创建用户失败,请稍后重试'); // 给前端一个明确的错误响应 } finally { if(client) await client.close(); // 用完记得关闭数据库连接 } });
按照这个步骤来,应该就能解决你的问题啦!
备注:内容来源于stack exchange,提问作者Nawsh
相关产品推荐
相关产品推荐

