在superagent函数中从GET获取数据
我正在尝试做这样的事情:
var countElemnts = function() { superagent .get('/someOtherUrl') .query({ type: value.type }) .end(function(err, res) { console.log(JSON.stringify(res.body)); if (res.ok) { reply(JSON.stringify(res.body)); } else { console.log(err); } }) }; superagent .post('/someUrl') .type('json') .send({ name: 'value.update', data: { id: request.params.id, type: value.type, count: countElemnts() } }) .end(function() { reply({ message: 'ok' }); });
在发送函数的数据选项中,我试图调用一个函数来获取一些值。
我想要得到的是回复正文中的价值,即res.body。 在console.log得到这个[{“count”:3}],但是如果我做一个console.log的res.body.count告诉我没有定义,我能做些什么来得到值3。
谢谢。
由于返回在"count "
中没有额外的空间(正如注释中所提到的),问题在于您试图访问数组的count
属性而不是对象(数组的第一个元素),所以访问它你应该这样做:
res.body[0].count
至于无法在您的POST中获得计数的问题,问题是countElemnts
使用asynchronous函数。 superagent的end
方法以函数作为参数,只有在收到响应时才被调用。 到那个时候,你的函数已经返回了( undefined
,因为你没有返回任何东西)。
您应该首先进行GET调用,然后将其发送给将处理POST的函数。 例如:
superagent .get('/someOtherUrl') .query({ type: value.type }) .end(function(err, res) { if (err) { console.log(err); } else { console.log(JSON.stringify(res.body)); sendCount(res.body[0].count) } }); function sendCount(count) { superagent .post('/someUrl') .type('json') .send({ name: 'value.update', data: { //id: request.params.id, // not sure where you are getting these values from, //type: value.type, // but you should adapt it to your code count: count } }) .end(function() { reply({ message: 'ok' }); }); }