1

There is a webpage http://ip2c.org/ and it parses any ip number to a country name, all I have to do is to give it an argument such as http://ip2c.org/10.0.1.3 (I know it's my local host, it's just for tests). When I run it in the browser, I'm seeing 1;ZZ;ZZZ;Reserved which is fine, I understand it's not an Ip address that can be reversed-geo tagged. But I expected to have a similar result in my node.js/angular app.

So far I created in my backend code a function:

app.get('/get/ip/address', function (req, res) {
    var ip = require('ip');
    res.json(ip.address());
})

and in my front end query controller:

$scope.countryName = function() {
    $http.get('/get/ip/address').success(function (data) {
        console.log(data);
        console.log("!!!!!");
        $http.get('http://ip2c.org/'+data).success(function (data) {
            console.log(data);
        })
    })
}

When I run it, I see:

queryCtrl.js:127 10.0.1.3 queryCtrl.js:128 !!!!! webpage.html:1 XMLHttpRequest cannot load http://ip2c.org/10.0.1.3. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access

How can I obey it and see the correct result in my console?

user3766930
  • 5,629
  • 10
  • 51
  • 104

1 Answers1

1

It is the server that decides what browsers can query it and whether a cross origin request is allowed or not. Your client-side angular code cannot change/fix that in any way. If the server isn't allowing a cross-origin request from the browser, then the browser just can't make that cross-origin request.

What you can do is move the functionality to your server. Here's how the sequence would work:

  • Client queries your server asking for country.
  • Your server gets the client IP address from that request.
  • Your server then makes a request to the ip2c.org URL to fetch the country.
  • Your server then returns that country to the angular client.

Since servers are not subject to cross-origin limitations (that is only a browser thing), you can have your server make the cross-origin request on your behalf.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Thank you so much! Could you tell me how could I modify my server side code to perform a call to ip2c.org? – user3766930 Jan 21 '16 at 23:20
  • 1
    @user3766930 - Just look at the `request()` module for nodejs. It shows you how to make http requests to other servers. – jfriend00 Jan 21 '16 at 23:42