Reputation: 2381
I start working with http request with NodeJS and I'm having a issue of the response returning undefined even though I check if it was not undefined.
fetch(urlRequest, {
method: 'post',
body: JSON.stringify(myJSONObject),
headers: {
'Authorization': `Basic ${base64.encode(`${key.APIKey}:${key.PasswordKey}`)}`,
'Content-Type': 'application/json'
},
})
.then(res => res.json())
.then(json => {
// This IF validation is not working
if(json.result.data !== undefined){
json.result.data.map(async (myDT) => {
const x = myDT;
console.log(x);
});
}
})
.catch(err => {
console.log(err)
});
The code fails in the catch with the error: TypeError: Cannot read property 'data' of undefined
Why isn't the IF condition working for json.result.data
?
Thanks
Upvotes: 0
Views: 79
Reputation: 160241
The error indicates json.result is undefined, so checking for json.result.data is insufficient.
Easiest solution is:
json && json.result && json.result.data !== undefined
Depending on the rest of your environment you may be able to use null-safe navigation (?.
, IIRC there's a Babel for this) or something like lodash get
or wrap it up in a Proxy
, and so on. JS is quite malleable.
Upvotes: 2