-1

I have create a nodejs server which will give response as ip address

app.get('/UserIP', function(req, res) {
    console.log(req.connection.remoteAddress);
  res.send(JSON.stringify({'ip':req.connection.remoteAddress}));
});

later i created a client which will get this ip address

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
 $(document).ready(function () {

    $.getJSON("http://localhost:7979/userip", function (data) {
                $('p').html('IP Address is: ' + res.ip);
    });
});
</script>
</head>
<body>
<p></p>
</body>
</html>

I cant get that ip to my client website.there are websites like jsonip.com which are working with my code. please help me in understanding where i m doing mistake.

Hari Krishna
  • 2,372
  • 2
  • 11
  • 24
  • Hi, have you tried to change localhost to any server?, also any errors or warnings? – Aren Hovsepyan Jan 31 '17 at 09:02
  • "I cant get that ip to my client website." — What is the problem? Do you get a different result to the one you expect? Does an error message show in the console in the browser's developer tools? Does the Network tab in the browser's developer tools show something unexpected? Does the *server side* `console.log()` statement fire (i.e. is the request even being received)? – Quentin Jan 31 '17 at 09:03
  • Routes are case-sensitive: you listen to `/UserIP`, but client sends request to `/userip` – Lyth Jan 31 '17 at 09:04
  • I tried with server also and it also giving output {"ip":"10.11.111.251"} for server and localhost but my client is not getting output – Hari Krishna Jan 31 '17 at 11:00

2 Answers2

0
  • If you have app.set('case sensitive routing', true); in your app , accessing "/userip" instead of "/UserIP" will not work. You have app.get('/UserIP' and $.getJSON("http://localhost:7979/userip".
  • In your jQuery code , you are accessing a "res" Object + res.ip) , even though you are returning a "data" function (data) Object.
Strahdvonzar
  • 400
  • 2
  • 10
0

The reason I am not able to get json is due to permitions.To fix this we need to fix it write this code in apt.get

res.setHeader("Access-Control-Allow-Origin", "*");

No other solution helped me.any way thanks for trying to help me.

Hari Krishna
  • 2,372
  • 2
  • 11
  • 24