0

I have to write a program where I need to fetch and display public IP of the client machine (windows) on the screen. For this I have this website (https://api.myip.com/) which provides the IP of the machine from where it is invoked. I am using JQuery/Ajax method to hit the URL (https://api.myip.com/) and capture the response.

Below is my code in index.js

$("#action-button1").click(function() {
    
   $.ajax({
      url: 'https://api.myip.com',
      data: {
         format: 'json'
      },
      error: function() {
         $('#info').html('<p>An error has occurred</p>');
      },
      dataType: 'jsonp',
      success: function(data) {
         var $ip = $('<h1>').text(data);
         $('#info')
            .append($ip)
      },
      type: 'GET'
   });
});

Now the issue is that when my above code runs, I see an error in Browser console. “Cross-Origin Read Blocking (CORB) blocked cross-origin response”. So I read further on internet and I see that suggestions are to add headers in response from server i.e. the server which hosts https://api.myip.com should send certain response headers to allow request from my code.

Now my question is what can be done from my code end to hit the URL https://api.myip.com successfully as I cannot make any change on server end.

PS: I am using spring boot to host my html and js file.

Edit1: If I keep dataType: 'jsonp' then I see warning on the browser console and if I change it to json then it shows red colored error of CORS.

Vaibhav Bhardwaj
  • 179
  • 1
  • 1
  • 9
  • The response from that API is JSON, not JSONP as you've set, and the two are not directly interchangeable. I presume you're tried to set JSONP as the response type due to some often given bad advice. The underlying problem is that the API you're using does not include CORS headers in the response. As such it cannot be called from client-side JS. You will need to make the call from the server side instead. – Rory McCrossan Mar 02 '21 at 19:28
  • Thanks Rory. That is where the real problem start. I could run this API from server end as well but in that case this will fetch public IP of the machine where server side code is executed. My original ask is to find out the public IP of client machine. – Vaibhav Bhardwaj Mar 02 '21 at 19:30
  • 1
    There are other IP retrieval APIs which do allow you to call them from JS: https://stackoverflow.com/questions/391979/how-to-get-clients-ip-address-using-javascript – Rory McCrossan Mar 02 '21 at 19:32
  • Thanks Rory. You made my day. – Vaibhav Bhardwaj Mar 03 '21 at 20:13

0 Answers0