6

I'm new in Vue.js. I need to get user ip address inside Vue.js.

What i have to do before is req.ip inside API, but my API always get Vue.js server IP.

So i think Vue.js that must determine what user ip is. But i still not find a best way to get user ip inside Vue.js. Anyone help ?

Crocodile
  • 469
  • 2
  • 8
  • 22
  • 1
    I don't understand what you are saying. Are you using SSR? – Sumurai8 Sep 09 '18 at 10:49
  • I want to get user/client ip address in Vue.js. If i try to get user ip via API, i just get Web server IP instead of user ip address. – Crocodile Sep 09 '18 at 11:00
  • 7
    Possible duplicate of [How to get client's IP address using JavaScript?](https://stackoverflow.com/questions/391979/how-to-get-clients-ip-address-using-javascript) – Sumurai8 Sep 09 '18 at 11:31
  • If i read Samurai8 reference, look like it is not independent technique to get user ip that visit our Website (in this case using Vue.js). If use Javascript native/Jquery way looks not simple. No alternative/simpler way to do it ? – Crocodile Sep 09 '18 at 13:06
  • There is no need for an application to know it's own ip. The ip you get in a regular ajax call is the remote ip (the ip of your server), because it needs to send data there. The remote server needs only to know the ip it sends data back to (in this case the client). There are some convoluted ways of determining your own ip in javascript, but I do not find them elegant, or consider them anyway stable. They are hacks/workarounds and should not be used. – Sumurai8 Sep 09 '18 at 21:06

2 Answers2

2

You need to send a request to expose the clients IP to some API. For instance you can do the following request with only vanilla JS (in mounted() for example) and then save the IP to data.

fetch('https://api.ipify.org?format=json')
  .then(response => response.json())
  .then(response => {
    this.clientIp = response.ip;
  });
0

I'm making a few assumptions here, but if you're using nodejs and express for your server behind a proxy, you can add this to have req.ip give you the client IP:

var app = express();
app.set('trust proxy', true);

Then your API idea would work.

jscuba
  • 106
  • 5