Marco Fedele
Marco Fedele

Reputation: 2148

Access-Control-Allow-Origin error with XMLHttpRequest

I'm developing a Django server. I need to get some data from an external service here.

Here is the JavaScript code that I'm using:

 function getDeclination(latitude, longitude) {

        var url = 'http://www.ngdc.noaa.gov/geomag-web/calculators/calculateDeclination';

        url += '?';
        url += 'lat1=' + latitude;
        url += '&'
        url += 'lon1=' + longitude;
        url += '&';
        url += 'resultFormat=xml';

        var xmlHttp = null;
        xmlHttp = new XMLHttpRequest();
        xmlHttp.open( "GET", url, false );

        xmlHttp.send();
        xml = xmlHttp.responseXML;

        var temp_d = xml.getElementsByTagName('declination');

        var string = temp_d[0].childNodes[0].nodeValue;

        string = string.substring(1, string.length - 2);

        return parseFloat(string);
    }

Using this code for a call like this getDeclination(46.0815605783, 13.2158580422) rise this error:

 XMLHttpRequest cannot load 
 http://www.ngdc.noaa.gov/geomag-web/calculators/calculateDeclination?lat1=46.0815605783&lon1=13.2158580422&resultFormat=xml. 
 Origin http://127.0.0.1:8000 is not allowed by Access-Control-Allow-Origin

How can I get rid of this problem and return to testing?

EDIT:

So I installed the middleware and the JS, but I can't get results. Perhaps I have done some error during the installation of the middleware, it's the first time for me. I know that Django found it, and that it's udsing it, but I don't know if I have done the setup correctly.

 XS_SHARING_ALLOWED_ORIGINS = "http://127.0.0.1:8000"
 XS_SHARING_ALLOWED_METHODS = ['POST','GET','OPTIONS', 'PUT', 'DELETE']  

I have put this code in settings.py, is this correct? Because I still get the same error.

Upvotes: 1

Views: 3486

Answers (2)

Marco Fedele
Marco Fedele

Reputation: 2148

In the end I implemented the code to get the declination from a server call.

For sake of completeness here is the code:

 import urllib2 
 from xml.dom.minidom import parseString

 # build the url
 def buildUrl(latitude, longitude):
    return settings.MAGNETIC_URL + '?' + 'lat1=' + str(latitude) + '&' + 'lon1=' + str(longitude) + '&' + 'resultFormat=xml'


 # load the page from the address       
 def retrieveWeb(address):

    try:                 
            web_handle = urllib2.urlopen(address)

    except urllib2.HTTPError, e: 
            error_desc = BaseHTTPServer.BaseHTTPRequestHandler.responses[e.code][0] 
            print "Cannot retrieve URL: HTTP Error Code", e.code, "Error: ", error_desc 
            sys.exit(1)         
    except urllib2.URLError, e: 
            print "Cannot retrieve URL: " + e.reason[1] 
            sys.exit(1)         
    except:                 
            print "Cannot retrieve URL: unknown error"                 
            sys.exit(1) 

    return web_handle  


 # main function to get declination
 def retrieveDeclination(lat, lng):

    # build url
    address = buildUrl(lat, lng) 

    # get the page
    page = retrieveWeb(address)

    # get xml
    xml = page.read()  

    page.close()

    # inizio il parsin
    dom = parseString(xml)

    #retrieve the first xml tag (<tag>data</tag>) that the parser finds with name tagName:
    xmlTag = dom.getElementsByTagName('declination')[0].toxml()

    #strip off the tag (<tag>data</tag>  --->   data):
    xmlData=xmlTag.replace('<declination>','').replace('</declination>','')

    # parse the output as float
    return float(xmlData)

Upvotes: 0

Matt
Matt

Reputation: 10322

Use this middleware while you're developing, and disable it when you put everything into production.

Edit:

As for the Javascript side of things, I've just tested this and it works ok. It does require jQuery and the middleware to be installed though.

function getDeclination(latitude, longitude){
    var url = "http://www.ngdc.noaa.gov/geomag-web/calculators/calculateDeclination";

    url += "?";
    url += "lat1=" + latitude;
    url += "&"
    url += "lon1=" + longitude;
    url += "&";
    url += "resultFormat=xml";

    $.ajax({
        url: url,
        success: function(data){
            var declination = parseFloat($(data).find("declination").text());
            alert(declination);
        }
    });
}

Upvotes: 1

Related Questions