Javascript 访问对象中的数据
当我运行上述代码时,我得到以下数据: {“debugCode”:null,“statusCode”:200,“numFound”:1,“结果”:[{“用户id”:“xxx510”,“创建的流地址”:“2019-03-05T16:13:01.982Z”,“流开发者id”:“f8b8fcb9-6f3e-4138-8c6b”-d0a7e8xxxxx@xxxx510,“设备开发者id”:raspberryPIxx@xxx510,“数据”:{“距离”:“12.4”,“状态”:“1”}}]} 如何使其仅显示状态 1)本例中没有中间件。。。你只是打电话来获取一些数据Javascript 访问对象中的数据,javascript,node.js,Javascript,Node.js,当我运行上述代码时,我得到以下数据: {“debugCode”:null,“statusCode”:200,“numFound”:1,“结果”:[{“用户id”:“xxx510”,“创建的流地址”:“2019-03-05T16:13:01.982Z”,“流开发者id”:“f8b8fcb9-6f3e-4138-8c6b”-d0a7e8xxxxx@xxxx510,“设备开发者id”:raspberryPIxx@xxx510,“数据”:{“距离”:“12.4”,“状态”:“1”}}]} 如何使其仅显示
2)
status
在body.results[0].data.status
中可用,因此只需使用它而不是整个body
对象即可,因为这样的代码没有问题。您确定您在body的数据字段中获得了距离和状态,还是预期的输出?通过在其上设置API密钥来尝试使用它们。我已经通过Promisify请求模块使用ES6标准重写了代码,或者您可以使用
这段代码中没有使用中间件,您可以从
response.statusCode
访问状态。很抱歉,我是node.js的新手。我尝试使用response.statusCode
之前,我得到了响应。但是我想要的状态是内部数据:,“data”:“distance”:“12.4”,“status”:“1”}]}
。我尝试使用response.results[0].data.status,但收到错误无法读取未定义的属性“0”
AFAIK,因此代码本身没有问题。您确定您在body的数据字段中获得了距离和状态,还是预期的输出?通过尝试使用他们的(API游乐场)[通过在其上设置API键。很抱歉,我是node.js的新手。我已经使用了它,但我得到了一个错误:无法读取未定义的属性“0”
,这通常意味着未为body定义results属性,您可能会遇到错误,因此添加if(error){console.log(error)}
在您的res.render()
之前,我设法解决了它。我需要先将它作为对象解析。我添加了JSON.parse(body)
并解决了它。谢谢您的帮助
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)
});
});
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')
}
});