0

On a new connection i get sometimes the error TypeError: Cannot read property 'country' of null and mostly it works correct!

How do i avoid this whenever its null so i will not get the error?

Error line is var location = geo.country;

        var ip =  socket.ip //socket.ip;
        var geo = geoip.lookup(ip);     
        var location = geo.country;
        console.log(location);
Inna
  • 393
  • 1
  • 3
  • 13

2 Answers2

1

Use a conditional:

var location = geo ? geo.country : "unknown";

The conditional operator is explained in detail here:

Question Mark in JavaScript

Community
  • 1
  • 1
Barmar
  • 596,455
  • 48
  • 393
  • 495
  • can you explain me what this do (I'm beginner) – Inna Feb 26 '15 at 17:11
  • I've added a link to a question that explains it. – Barmar Feb 26 '15 at 17:13
  • @Inna I'm running on 127.0.0.1 for example. This ip address is in no way connected to a country, so Barmar'a answer simply assigns the country "unknown" to ip address (like 127.0.0.1) . Very nice. – basickarl Sep 26 '15 at 12:02
0

It means you are getting null.country which according to your code, means geo is returning null. That also means your geoip is not working. Do console.log() to check if your geoip is returning value or null.

Thinkerer
  • 1,568
  • 4
  • 21
  • 40