在一个新的连接上,我有时会收到错误TypeError: Cannot read property 'country' of null
,而且大多数情况下都是正确的!
当它为null时,我如何避免它,这样我就不会得到错误?
错误线为var location = geo.country;
var ip = socket.ip //socket.ip;
var geo = geoip.lookup(ip);
var location = geo.country;
console.log(location);
使用条件:
var location = geo ? geo.country : "unknown";
这里详细解释了条件运算符:
JavaScript 中的问号
这意味着你正在获得null.country
,根据你的代码,这意味着geo正在返回null
。这也意味着你的大地水准面不起作用。执行console.log()检查您的geoap是否返回值或null。