18

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();
  • This XMLHttpRequest is not a browser call, rather in an application that support XMLHttpRequest.

3 Answers 3

40

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.

Sign up to request clarification or add additional context in comments.

Comments

8

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"})

Comments

-1
downloadReportFile(id, query): Observable<Object[]> {
var url = `${environment.baseUrl}report?report_name=${id}${query}`;

return Observable.create(observer => {

  let xhr = new XMLHttpRequest();

  xhr.open('GET', `${url}`, true);
  xhr.setRequestHeader(environment.AUTH_TOKEN_HEADER_KEY, 'Bearer '+ 
  localStorage.getItem(environment.AUTH_TOKEN_STORE_KEY));
  xhr.responseType = 'blob';

  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {

        let filename = "Claim_Report.csv"
        var contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        var blob = new Blob([xhr.response], { type: "text/plain;charset=utf-8" });
        if (typeof window.navigator.msSaveBlob !== 'undefined') {

          window.navigator.msSaveBlob(blob, filename);
          return;
        }

        const blobURL = window.URL.createObjectURL(blob);
        const tempLink = document.createElement('a');
        tempLink.style.display = 'none';
        tempLink.href = blobURL;
        tempLink.setAttribute('download', filename);

        if (typeof tempLink.download === 'undefined') {
          tempLink.setAttribute('target', '_blank');
        }
        document.body.appendChild(tempLink);
        tempLink.click();
        document.body.removeChild(tempLink);
        setTimeout(() => {
          // For Firefox it is necessary to delay revoking the ObjectURL
          window.URL.revokeObjectURL(blobURL);
        }, 100);
      } else {
        observer.error(xhr.response);
      }
    }
  }
  xhr.send();

});
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.