res.send(body.data) 是未定义的



>im 试图使用节点请求获取另一个 API,但是当我尝试显示 body.data 时,它的返回未定义

router.get('/',  (req, res,next) => {
request('http://localhost:3000/api/v1/promos',  (error, response, body) => {
if(error) { 
res.send('An erorr occured')
console.log(error)
}
else {
res.send(body.data)
}
});
});

谁知道出了什么问题

如果你的请求正文是JSON,那么你必须解析它以将其转换为Javascript对象,以便你可以访问.data属性。

您可以通过将json: true选项传递给request()来执行此操作,它将为您解析 JSON。

或者,您可以使用let result = JSON.parse(body)手动解析正文。


以下是设置json: true选项的方法:

router.get('/',  (req, res,next) => {
request({
url: 'http://localhost:3000/api/v1/promos',
json: true
},  (error, response, body) => {
if(error) { 
res.send('An erorr occured')
console.log(error)
}
else {
res.send(body.data)
}
});
});

相关内容

最新更新