NodeJS:访问对象字段返回未定义,即使字段存在

NodeJS: Accessing object fields returns undefined even though fields exist

本文关键字:字段 存在 未定义 返回 访问 对象 NodeJS      更新时间:2023-09-26
router.get('/:id', function(req, res, next){console.log(req.params.id)
  request(
    config.API_URL + "/v1/gallery/get?id=" + req.params.id, 
    function (err, response, body){
      console.log('###BODY###',JSON.stringify(body));
      console.log('###BODY###',JSON.stringify(body.data));
      res.render('gallery', { user: req.session.user, gallery: body.data, title: 'Gallery', purchased: req.session.user.outlet ? (req.session.user.outlet.purchased || []) : [], config: config });
    }
  );
});

我试图传递请求体的数据字段作为此模板的库,但在传递body.data时,在模板中它说我的库参数未定义。正如您在上面看到的,我然后控制台记录了主体,然后是它的字段。console.log(body)产生以下输出:

###BODY### "{'"err'":null,'"data'": {'"_id'":'"5d955d7431d34f862a0dbd60'",'"owner '":null,'"caption'":'"A suspected shooting at the Washington DC Navy Yard has sh ut down parts of the city. This is the same location where a gunman killed 12 pe ople in 2013. After an investigation search, authorities gave the '''"all clear. '''"'",'"tags'":['"dc'",'"navyyard'",'"shooting'",'"washington'"]...

我缩短了输出,但正如您所看到的,数据字段显然在data.err旁边。但是,当我运行console.log('###BODY###',JSON.stringify(body.data))时,返回的是###BODY### undefined。有人能解释一下这种行为吗?

替换为

request(
    config.API_URL + "/v1/gallery/get?id=" + req.params.id,
    <callback>
);

:

request({
    url: config.API_URL + "/v1/gallery/get?id=" + req.params.id,
    json: true
}, <callback>);

这将指示request自动将响应体解析为json(当然,假设您正在使用此请求模块)。