NodeJS:即使字段存在,访问对象字段也会返回undefined

时间:2015-07-22 18:46:47

标签: javascript node.js

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。有人能解释一下这种行为吗?

1 个答案:

答案 0 :(得分:3)

替换它:

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(假设您正在使用this request module)。