如何将Express POST路由中req.body的值传递到API模块?
解决方法
首先明确错误根源:你在app.js的POST路由中已经正确获取到req.body的字段,但调用api_list.js的addNewGame时,传入的是{title, genre, platform}对象,而该函数期望接收完整的req请求对象——函数内部尝试解构req.body,但你传的参数根本没有body属性,因此触发报错。
提供两种直接可行的修复方案:
方案一:修改api_list.js的addNewGame函数,直接接收游戏数据对象
既然已经在路由层拿到了具体字段,没必要传递整个req对象,调整函数参数为直接接收游戏数据:
// api_list.js 中的 addNewGame 函数 function addNewGame(app, pool, userId, functionName, gameData) { // 从传入的gameData中解构字段,而非req.body const { title, genre, platform } = gameData; // 执行数据库插入逻辑示例 const insertQuery = ` INSERT INTO games (title, platform, genre, user_id) VALUES ($1, $2, $3, $4) RETURNING *; `; return pool.query(insertQuery, [title, platform, genre, userId]); }
然后在app.js的POST路由中保持现有调用方式即可:
// app.js 的 POST / 路由 app.post('/', (req, res) => { const { title, genre, platform } = req.body; api_list.addNewGame(app, pool, userId, 'addNewGame', { title, genre, platform }) .then(() => res.redirect('/')) .catch(err => console.error('插入失败:', err)); });
方案二:传递完整的req对象给addNewGame
如果不想修改api_list.js的函数定义,直接在路由中传递完整的req对象:
// app.js 的 POST / 路由 app.post('/', (req, res) => { // 直接传入req,而非单独的字段对象 api_list.addNewGame(app, pool, userId, 'addNewGame', req) .then(() => res.redirect('/')) .catch(err => console.error('插入失败:', err)); });
这样函数内部就能正常解构req.body,因为此时req是完整的Express请求对象。
额外验证点
虽然你说读取功能正常,但再次确认body-parser的配置是否覆盖了表单提交的格式:
// app.js 中确保配置了urlencoded解析 const bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: true }));
表单默认使用application/x-www-form-urlencoded格式,这个中间件是必须的。
内容的提问来源于stack exchange,提问作者nezza1
相关产品推荐
相关产品推荐

