我正在使用Express从外部API收集JSON响应,一些元素的值作为null返回给我。当我稍后尝试使用这些值(以及其他值)时,我得到了TypeError: Cannot read property 'avatar' of null错误。我试着覆盖它,但它总是返回null。当这个特定的参数值为"null“时,我可以跳过或覆盖它吗?下面是我的代码中我遇到问题的部分:
var clearbit = require('clearbit')(apikey);
clearbit.Enrichment.find({email: email, stream: true})
.then(function (response) {
var person = response.person;
var company = response.company;
res.render('single-user', {
// any of below can be equal to null depending on the email that is being checked
avatar: person.avatar,
name: person.name.fullName,
email: person.email,
//other properties
});
})发布于 2020-04-25 09:52:19
您可以使用新引入的可选链接(?.)来解决这个问题。您的代码将如下所示:
var clearbit = require('clearbit')(apikey);
clearbit.Enrichment.find({email: email, stream: true})
.then(function (response) {
var person = response.person;
var company = response.company;
res.render('single-user', {
avatar: person?.avatar,
name: person?.name?.fullName,
email: person?.email,
// Similarly for all properties
});
})这里有一个供参考的链接:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
希望这能有所帮助:)
https://stackoverflow.com/questions/61419950
复制相似问题