[英]Node.js Cannot read property of undefined using JSON data
I'm trying to convert a js script to a node.js script.我正在尝试将 js 脚本转换为 node.js 脚本。 The JS script works fine, and managed to pull data from this URL and correctly use the information.
JS 脚本运行良好,并设法从该 URL 中提取数据并正确使用这些信息。 However, when I try run it on Node.js, I get the error
"Cannot read property of 'fixtures' undefined."
但是,当我尝试在 Node.js 上运行它时,出现错误
"Cannot read property of 'fixtures' undefined."
I've added this package to pull the data, however I'm not sure why it's now throwing an error.我已经添加了这个包来提取数据,但是我不确定为什么它现在会抛出错误。
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
//Get Data
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.send();
};
//Use Data
getJSON('http://api.football-data.org/v1/teams/343/fixtures',
function(err, data) {
if (err !== null) {
console.log(" An error has occured.")
} else {
var latest;
for(x = 0; data.fixtures[x].status !== "TIMED"; x++) {
latest = data.fixtures[x].matchday - 1;
}
}};
The error is thrown at the line while(data.fixtures[x].status !== "TIMED")
, and the error is错误是在
while(data.fixtures[x].status !== "TIMED")
行抛出的,错误是
for(x = 0; data.fixtures[x].status !== "TIMED"; x++) {
^
TypeError: Cannot read property 'fixtures' of undefined
Please could you explain to me why JS can see the data and use it fine, but node.js sees the property to be undefined?请你向我解释为什么 JS 可以看到数据并可以正常使用它,但 node.js 看到该属性未定义?
Many thanks.非常感谢。
EDIT: Removed legacy while loop that shouldn't have been there.编辑:删除了不应该存在的遗留 while 循环。
The response
property is part XMLHttpRequest Level 2 , but xmlhttprequest
only supports 1 at the moment: response
属性是XMLHttpRequest Level 2 的一部分,但xmlhttprequest
只支持 1:
Note: This library currently conforms to XMLHttpRequest 1.
注意:这个库目前符合 XMLHttpRequest 1。
For this reason xhr.response
will be undefined
.为此,
xhr.response
将是undefined
。
Only xhr.responseText
will be set, and this is a string so you would need to add the parsing of json yourself.只会设置
xhr.responseText
,这是一个字符串,因此您需要自己添加 json 的解析。
if (status === 200) {
try { // use a try block here in case the the response is not parseable
callback(null, JSON.parse(xhr.responseText));
} catch(e) {
callback(e)
}
} else {
callback(status, xhr.response);
}
The reason you're getting that message is because the variable data
in your callback is undefined
.您收到该消息的原因是回调中的变量
data
是undefined
。 The reason it is so is that you are passing it that原因是你正在通过它
callback(null, xhr.response); //<-- You should have used responseText
But even that will not solve the issue - it is text not json.但即使这样也不能解决问题——它是文本而不是 json。 So parse it
所以解析它
callback(null, JSON.parse(xhr.responseText));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.