访问对象内的数据

问题描述 投票:-1回答:2
app.get('/profile/:id', function(req, res){
var options = { method: 'GET',
    url: 'https://api.favoriot.com/v1/streams?max=1',
    headers: 
    { 'cache-control': 'no-cache',
        'content-type': 'application/json',
        'apikey': 'api key' } };

    request(options, function (error, response, body) {  
            res.render('profile', {data:body});
    console.log(body)
    });
});

当我运行上面的代码时,我得到这些数据:

{ “debugCode”:空 “的StatusCode”:200, “numFound”:1, “结果”:[{ “USER_ID”: “xxx510”, “stream_created_at”: “2019-03-05T16:13:01.982Z”, “stream_developer_id”: “f8b8fcb9-6f3e-4138-8c6b-d0a7e8xxxxx @ xxxx510”, “device_developer_id”: “raspberryPIxx @ xxx510”, “数据”:{ “距离”: “12.4”, “状态”: “1”}} ]}

如何才使其仅显示状态?

javascript node.js
2个回答
0
投票

AFAIK这样的代码没有问题。您确定您在身体的数据字段中获得了距离和状态,还是预期的输出?通过在其上设置API密钥尝试使用他们的API playground。我通过promisifying request模块使用ES6标准重写了代码,或者你可以使用request-promise-native

function requestPromisified(options) {
  return new Promise(function(resolve, reject) {
    request(options, function(error, res, body) {
      if (!error && res.statusCode == 200) {
        resolve(body);
      } else {
        reject(error);
      }
    });
  });
}

app.get("/profile/:id", async (req, res) => {
  const options = {
    method: "GET",
    url: "https://api.favoriot.com/v1/streams?max=1",
    headers: {
      "cache-control": "no-cache",
      "content-type": "application/json",
      apikey: "api key"
    }
  };
  try {
    const body = await requestPromisified(options);
    console.log(body);
    res.render("profile", { data: body });
  } catch (error) {
      res.status(400).send('Unable to find a profile')
  }
});

0
投票

1)在这个例子中没有中间件......你只是打电话来获取一些数据。

2)status可以在body.results[0].data.status中使用,所以只需使用它而不是整个body对象

© www.soinside.com 2019 - 2024. All rights reserved.