for...in循环访问req.body属性值出现undefined的原因与解决方法
问题:for...in循环中访问req.body属性始终返回undefined
我尝试在for...in循环中用属性名访问req.body.id、req.body.title等对应属性的值,但结果一直是undefined。代码示例如下:
const HttpError = require('../models/http-error') const { v4: uuidv4 } = require('uuid'); const { v4 } = require('uuid'); const DUMMY_PLACES = [ { id: 'p1', title: 'Empire State Building', description: 'One of the most famous sky scrapers in the world!', location: { lat: 40.7484474, lng: -73.9871516 }, address: '20 W 34th St, New York, NY 10001', creator: 'u1' } ]; const updatePlace = (req, res, next) => { const placeId = req.params.pid; // const { id, title, description, coordinates, address, creator } = req.body; const placeIndex = DUMMY_PLACES.findIndex(p=> p.id === placeId); const targetPlace = DUMMY_PLACES[placeIndex]; console.log(req.body); for (const property in targetPlace) { console.log(req.body.property); if (targetPlace[property] !== req.body.property) { targetPlace[property] = req.body.property; }; }; res.status(204).json({place:targetPlace}); }; exports.getPlaceById = getPlaceById; exports.getPlaceByUserId = getPlaceByUserId; exports.createPlace = createPlace; exports.updatePlace = updatePlace;
成因分析
问题核心是属性访问的语法错误:
- 你使用
req.body.property这种点语法时,JavaScript会将property视为固定字符串属性名,而非循环中动态的变量值。也就是说,代码一直在尝试读取req.body里名为"property"的属性,而非当前循环的id、title等目标属性,因此返回undefined。
修复方案
- 改用方括号语法访问动态属性:将所有
req.body.property替换为req.body[property],让JavaScript解析变量property的实际值,从而访问对应属性。 - 添加属性存在性检查:避免把undefined赋值给
targetPlace的属性(比如req.body未传递某个字段时)。 - 调整响应状态码:HTTP 204状态码要求响应体为空,这里返回了JSON数据,改成200更符合规范。
- 可选:处理嵌套对象更新:如果需要深层更新
location这类嵌套对象,需单独处理,否则会直接覆盖整个对象。
修改后的完整代码
const HttpError = require('../models/http-error') const { v4: uuidv4 } = require('uuid'); const { v4 } = require('uuid'); const DUMMY_PLACES = [ { id: 'p1', title: 'Empire State Building', description: 'One of the most famous sky scrapers in the world!', location: { lat: 40.7484474, lng: -73.9871516 }, address: '20 W 34th St, New York, NY 10001', creator: 'u1' } ]; const updatePlace = (req, res, next) => { const placeId = req.params.pid; const placeIndex = DUMMY_PLACES.findIndex(p => p.id === placeId); if (placeIndex === -1) { // 可选:处理找不到对应地点的情况 return next(new HttpError('无法找到要更新的地点', 404)); } const targetPlace = DUMMY_PLACES[placeIndex]; console.log(req.body); for (const property in targetPlace) { // 只更新req.body中存在且不为undefined的属性 if (req.body.hasOwnProperty(property) && req.body[property] !== undefined) { // 特殊处理嵌套的location对象(如果需要深层更新) if (property === 'location' && typeof req.body[property] === 'object') { Object.assign(targetPlace[property], req.body[property]); } else { targetPlace[property] = req.body[property]; } } } res.status(200).json({ place: targetPlace }); }; exports.getPlaceById = getPlaceById; exports.getPlaceByUserId = getPlaceByUserId; exports.createPlace = createPlace; exports.updatePlace = updatePlace;
内容的提问来源于stack exchange,提问作者s c
相关产品推荐
相关产品推荐

