I'm trying to convert a js script to a node.js script. The JS script works fine, and managed to pull data from this URL and correctly use the information. However, when I try run it on Node.js, I get the error "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
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?
Many thanks.
EDIT: Removed legacy while loop that shouldn't have been there.
datain the code snippet, butfbdatain the error message. Maybe you mistyped the variable name?xand then reset it back to zero?