Express+MySQL+Postman中POST请求报错:无法读取undefined的product_title属性
排查并解决Express POST接口的"Cannot read properties of undefined (reading 'product_title')"错误
错误根源
这个错误直接说明req.body是undefined——你尝试读取它的product_title属性自然会报错,因为Express默认不会自动解析POST请求的请求体,必须手动配置中间件才能获取req.body。
解决步骤
1. 给Express添加请求体解析中间件
在你的路由代码(比如app.post("/product"))之前,添加以下中间件配置:
// 解析JSON格式的请求体 app.use(express.json()); // 解析表单格式的请求体(如果需要处理form-data或x-www-form-urlencoded) app.use(express.urlencoded({ extended: true }));
注意:中间件必须放在所有路由定义之前,否则路由无法获取解析后的req.body。
2. 检查Postman的请求配置
确保你的POST请求符合要求:
- 确认请求方法是POST,目标URL正确(比如
http://localhost:3000/product)。 - 切换到Body标签,根据你发送的数据格式选择对应选项:
- 若发送JSON数据:选择
raw,格式下拉框选JSON,输入正确的JSON内容(注意引号是双引号):
Postman会自动添加{ "product_title": "测试商品", "product_price": 99.9, "product_type": "电子产品", "product_brand": "测试品牌" }Content-Type: application/json请求头,无需手动设置。 - 若发送表单数据:选择
form-data或x-www-form-urlencoded,逐个添加product_title、product_price等字段和对应值。
- 若发送JSON数据:选择
3. 优化代码中的异步逻辑(可选但推荐)
你当前代码里await和db.query的回调混用是无效的——db.query的回调版本不返回Promise,await不会等待查询完成就直接执行res.send("Added"),可能导致响应提前发送。可以改成Promise形式:
app.post("/product", async (req, res, next) => { try { let product = { product_title: req.body.product_title, product_price: req.body.product_price, product_type: req.body.product_type, product_brand: req.body.product_brand, }; let sql = `INSERT INTO products SET ?`; // 改用Promise形式的db.query(如果你的数据库支持,比如mysql2/promise) const result = await db.query(sql, product); console.log(result); res.send("Added"); } catch (err) { // 用next传递错误给Express的错误处理中间件,避免崩溃 next(err); } });
内容的提问来源于stack exchange,提问作者user19347248
相关产品推荐
相关产品推荐

