[GIS] ArcGIS JavaScript setRequestPreCallback is partially working

arcgis-10.3arcgis-javascript-apiarcgis-server

I have an api sitting in front of AGS that requires it's own authentication. I am using setRequestPreCallback as stated by the ESRI docs.

In the image below, you can see that the first 2 requests are returning 200. The first request is CORS Preflight and the second request is the JS api getting the json info from the MapServer.

enter image description here

The second request uses the function I have set in setRequestPreCallback(…) to properly set a header value with the token. However, whenever an image is requested from the MapServer (via export), the function I have in setRequestPreCallback is not called and the token is not set, leaving me with a bunch of 401 Unauthorized requests.

I am running AGS 10.3 with JS API 3.14

Here is the JS I am using:

require([
    "esri/map",
    'esri/request',
    'esri/config',
    "esri/layers/ArcGISDynamicMapServiceLayer",
    "dojo/domReady!"
], function(Map, esriRequest, esriConfig, ArcGISDynamicMapServiceLayer) {

  esriConfig.defaults.io.corsEnabledServers.push("my.url.com");

  var map = new Map("mapDiv", {
    center: [-118, 34.5],
    zoom: 8,
    basemap: "topo"
  });

  function myCallbackFunction(args) {

    if (args.url.indexOf('my.url.com') === -1) {
        return args;
    }

    args.headers = args.headers || {};
    args.headers.token = 'token';

    return args;
  }

  esriRequest.setRequestPreCallback(myCallbackFunction);

  map.addLayer(new ArcGISDynamicMapServiceLayer("https://my.url.com/map/Assets_Service/MapServer"));
});

Any ideas?

Best Answer

Instead of using a setRequestPreCallback, you can just append the token to the MapService, and the JSAPI will send it along:

new ArcGISDynamicMapServiceLayer("https://my.url.com/map/Assets_Service/MapServer?token=" + token);

Related Question