My api call requires me to pass the api key in the headers, but I'm getting error back from the api service {"error":"2424452","message":"Invalid Api Key"}
I know my api key is valid as I can make the same api call in Python just fine, example:
req = requests.Session()
req.headers.update({'x-api-key': 'my-api-key', 'X-Product': 'my-product-name'})
req.get(url)
But in javscript, the same call errors out. I believe I'm not setting the headers correctly or something?
var req = new XMLHttpRequest();
req.onreadystatechange=handleStateChange;
req.open("GET", "url", true);
req.setRequestHeader("Host", "api.domain.com", "x-api-key", "my-api-key", "X-Product", "my-product-name");
req.send();
XMLHttpRequest
is not a browser call, rather in an application that support XMLHttpRequest
.Synchronous and asynchronous requests XMLHttpRequest supports both synchronous and asynchronous communications. In general, however, asynchronous requests should be preferred to synchronous requests for performance reasons. Synchronous requests block the execution of code which causes "freezing" on the screen and an unresponsive user experience.
To do the request, we need 3 steps: Create XMLHttpRequest: let xhr = new XMLHttpRequest(); The constructor has no arguments. Initialize it, usually right after new XMLHttpRequest: xhr.open( method, URL, [ async, user, password]) This method specifies the main parameters of the request: method – HTTP-method. Usually "GET" or "POST".
Asynchronous request. If you use an asynchronous XMLHttpRequest, you receive a callback when the data has been received. This lets the browser continue to work as normal while your request is being handled.
All new XHR features such as timeout or abort are not allowed for synchronous XHR. Doing so will raise an InvalidAccessError. This example demonstrates how to make a simple synchronous request. Line 3 sends the request. The null parameter indicates that no body content is needed for the GET request.
setRequestHeader
sets one header and takes two arguments (the name and the value).
If you want to set multiple headers, then call setRequestHeader
multiple times. Don't add extra arguments to the first call.
In case you don't want to set multiple headers explicitly you can use
function setHeaders(headers){
for(let key in headers){
xhr.setRequestHeader(key, headers[key])
}
}
setHeaders({"Host":"api.domain.com","X-Requested-With":"XMLHttpRequest","contentType":"application/json"})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With