I have been making calls to a previously free API using esriRequest
var layersRequest = esriRequest({
url: base_url,
content: {
"latitude": lat,
"longitude": long,
"riskCategory": risk,
"siteClass": siteClass,
"title":"Default"},
dataType:'jsonp',
handleAs: "json",
callbackParamName: "callback" }); ...
Now the API requires a key; which I have:
const key = 'xI234fg543example23';
The above is just an **example key; not real
The API documentation says to "Include your key in the api-key field of your request headers to authenticate like this:
curl --header "api-key: [your_api_key]" -X GET "https://api-hazards.atcouncil.org/public/v1/[load_category].json?lat=[lat]&lng=[lng]"
How do I correctly apply this using esriRequest
? I believe the generic javascript equivalent would be
layerRequest.setRequestHeader
You would want to use a request interceptor.
https://developers.arcgis.com/javascript/latest/api-reference/esri-config.html#request
This is a property you can set on "esri/config".
There is an option to provide additional headers to requests that are made to specific URLs.
https://developers.arcgis.com/javascript/latest/api-reference/esri-config.html#RequestInterceptor
Your case may look something link this.
esriConfig.request.interceptors.push({
urls: "https://api-hazards.atcouncil.org",
headers: {
"api=key": "xI234fg543example23"
}
});
That should give you the results you are looking for.
Realized you might be using 3x. In 3x, there is a method on esriRequest you can use to do something similar.
esriRequest.setRequestPreCallback(function(ioArgs) {
if (ioArgs.url.indexOf("https://api-hazards.atcouncil.org") > -1) {
ioArgs.headers = ioArgs.headers || {}; // make sure headers are not null
ioArgs.headers["api-key"] = "xI234fg543example23" // add custom headers
}
return ioArgs;
});
OK, I am trying to apply setRequestPreCallback to my situation based on the documentation. First, created a function:
xI234fg543example23
" // add custom headersThen I tried calling the function before I make my esriRequest (which is inside a button click event).
Right now I am getting a net::ERR_ABORTED 401 (Unauthorized) error. I tested the API Key in Postman and it worked. Do you see anything I am doing incorrectly in applying this?
Hi Justin,
You might want to use Fiddler or Chrome developer windows at network tab, check the network traffic.
And find out whether esriRequest object is performing your expected http request to the destination.
Check that whether there is header, params you want.
Step to do:
Open your page in chrome, press f12, break point on the code before it is called.
And switch to network tab and check the network traffic