9

I am tyring to add code to get the ipaddress of the user on my site. I am using a react(mobx/mst) with axios.

   getIpAddress: flow(function*() {

    const response = yield axios.get('http://api.ipify.org/?format=text');
    self.ipAddress = response.data;  

    })

Access to XMLHttpRequest at 'http://api.ipify.org/' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
chobo2
  • 83,322
  • 195
  • 530
  • 832

1 Answers1

15

It's typical CORS issue. Server doesn't allow your client to gather information directly. You should use some server-side proxy or use https://cors-anywhere.herokuapp.com/, so your code would look like this

getIpAddress: flow(function*() {
  const response = yield axios.get('https://cors-anywhere.herokuapp.com/http://api.ipify.org/?format=text');
  self.ipAddress = response.data;  
})
viciousP
  • 510
  • 3
  • 14
  • Sorry your code looks like my code? What did you add? I also don't understand how the Jquery ajax (it is one of their examples: https://www.ipify.org/) works but not axios – chobo2 Apr 11 '19 at 22:12
  • sorry, I just edited my answer, please check it again – viciousP Apr 11 '19 at 22:14
  • Thanks, that does work, but still not clear why something like jquery works and not axios. – chobo2 Apr 11 '19 at 22:16
  • axios and jquery are probably using pretty similar implenentation of native fetch API, it wouldn't work either on jquery. You can read more about CORS on official MDN site here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS – viciousP Apr 11 '19 at 22:19
  • Ok, I will check that out, just going my the fact they list an example on how to grab the ip using jquery ajax, so would figure that it would work. – chobo2 Apr 11 '19 at 22:19
  • It does mean that server doesn't accept requests different than it's origin. (like your localhost etc.) They probably only provide server-side libraries to interact with their API. Does this answer satisfy you? – viciousP Apr 11 '19 at 22:23
  • Yep still think it is weird they got a javascript and jquery example which don't seem to be running server side, anyways what you posted works and I will go with that. – chobo2 Apr 12 '19 at 04:49
  • 1
    Can I get the client ipaddress using cors-anywhere? It seems to be the ipaddress of the server that runs cors-anywhere application. – wafe Feb 07 '21 at 02:10
  • 2
    I wonder if we are getting the ip address of the server or the client when we go through proxy... – TienPing Apr 21 '21 at 05:38