DevonTaig
DevonTaig

Reputation: 711

XMLHttpRequest throwing error on valid URL

I'm new to using XMLHttpRequest, and I guess I'm missing something pretty obvious - I have a perfectly valid URL that I am trying to retrieve JSON data from that, but when I call send on onerror function executes, but onload doesn't (even though I get a 200 back). You can see the test page here: https://pwas.resourcedata.com/walkipedia/webrequest.html

        function MakeWebRequest() {
        url = "https://data.wsdot.wa.gov/arcgis/rest/services/Shared/TownshipSection/MapServer/identify?geometry=-13606913.506613478%2C5937651.515662&geometryType=esriGeometryPoint&sr=&layers=all&layerDefs=&time=&layerTimeOptions=&tolerance=1&mapExtent=-13609094.35057674%2C5936620.810108784%2C-13602038.257402979%2C5939181.450556404&imageDisplay=400%2C300%2C96&returnGeometry=true&maxAllowableOffset=&geometryPrecision=&dynamicLayers=&returnZ=false&returnM=false&gdbVersion=&f=pjson";
        let xhr = new XMLHttpRequest();

        xhr.onload = function () {
            debugger;
            let data = JSON.parse(xhr.responseText);

        }

        xhr.onerror = function (x ) {
            alert("Error while calling Web API");
        }

        let httpVerb = "GET";

        xhr.open(httpVerb, url);

        xhr.setRequestHeader("Content-Type", "application/json");

        xhr.send();
    }

Upvotes: 0

Views: 241

Answers (2)

Sandeep Patel
Sandeep Patel

Reputation: 5148

Remove this line :

 xhr.setRequestHeader("Content-Type", "application/json");

please check this fiddle for the output : https://jsfiddle.net/2e9jz6x3/2/

Upvotes: 0

Barmar
Barmar

Reputation: 782498

Remove this line:

xhr.setRequestHeader("Content-Type", "application/json");

It's not necessary, since GET requests don't have any content (the JSON is in the response). And it's triggering a CORS validation error.

If you want to specify that you're only expecting a JSON response, use:

xhr.setRequestHeader("Accept", "application/json");

Upvotes: 1

Related Questions