[英]Cannot extract key/value from json
A resource is fetched in node.js like this: 在node.js中获取资源,如下所示:
requestify.post('myurl')
.then(function (response) {
console.log(response);
console.log(response.body);
});
console.log(response) gives: console.log(响应)给出:
Response {
code: 200,
body: '{"guid":"abcd","nounce":"efgh"}'
}
console.log(response.body) gives: console.log(response.body)给出:
{"guid":"abcd","nounce":"efgh"}
However, for some reason I cannot access the key "guid" or "nounce". 但是,出于某种原因,我无法访问密钥“guid”或“nounce”。 In both cases I get an undefined.
在这两种情况下,我得到一个未定义。 I have tried both with
我试过两个
console.log(response.body.guid);
and 和
console.log(response.body['guid']);
The body is string, but you want it to be an object. 正文是字符串,但你希望它是一个对象。 Just transform it:
只需转换它:
JSON.parse(response.body).guid
It seems that the value of body
property is a string. 似乎
body
属性的值是一个字符串。 You must parse it as JSON: 您必须将其解析为JSON:
console.log(JSON.parse(response.body).guid);
You need to set the return type to 您需要将返回类型设置为
response.writeHead(200, {"Content-Type": "application/json"});
so your receiving end will make it an object automagically when received. 因此,您的接收端将在收到时自动将其作为对象。 See Responding with a JSON object in NodeJS (converting object/array to JSON string)
请参阅使用NodeJS中的JSON对象进行响应(将对象/数组转换为JSON字符串)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.