AnsweredAssumed Answered

How to set headers for esriRequest using .setRequestPreCallback()

Question asked by jbridwell_Dewberry on Jul 2, 2019
Latest reply on Jul 8, 2019 by jbridwell_Dewberry

I want to add an api-key to the header of my esriRequest. I first created a callback function. 

function myCallbackFunction(ioArgs){
            ioArgs.headers = ioArgs.headers || {}; // make sure headers are not null
            ioArgs.headers["api-key"] = "<123mykey>" // add custom headers
            return ioArgs;
    }

My esriRequest is triggered by a button click after the lat, long have been captured. I placed by .setRequestPreCallback() that calls my myCallbackFunction right before the request is made, inside the click event.

document.getElementById("btnGetWindspeed").onclick = function () {
 if (additionalInfo["pointGeomOfInterest"] !== undefined) {
    var lat = additionalInfo["pointGeomOfInterest"].y;
    var long = additionalInfo["pointGeomOfInterest"].x;
  }

  if (additionalInfo["pointGeomOfInterest"] === undefined) {
        alert("Choose a location!");
  } else {
    var base_url = wind_url + "wind.json";
    var lat = additionalInfo["pointGeomOfInterest"].y;
    var long = additionalInfo["pointGeomOfInterest"].x;
    esriRequest.setRequestPreCallback(myCallbackFunction);
    var windRequest = esriRequest({
    url: base_url,
    content: { "lat": lat,
    "lng": long
    },
    dataType:"jsonp",
    handleAs: "json",
    callbackParamName: "callback"
    });
    windRequest.then(
    function(response) {
    wind_data = response.response.data;
    console.log("Success: ", wind_data);
    addWindspeedTable(wind_data);
  }, function(error) {
    console.log("Error: ", error.message);
  });
};

 

However, the callback function fails and I get the following error that the api has not been authorized: `Failed to load resource: the server responded with a status of 401 (Unauthorized)`. Am I adding the headers incorrectly, utilizing the .setRequestPreCallback() wrong, or is something else going on? Note: I have validated the api key and url in Postman and gotten a correct response.

                                                                                                                               

Outcomes