joke4me
joke4me

Reputation: 842

How to set multiple headers data with XMLHttpRequest in async mode?

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();

Upvotes: 18

Views: 27928

Answers (3)

Bilal Alam
Bilal Alam

Reputation: 894

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

Upvotes: 8

Shashwat Gupta
Shashwat Gupta

Reputation: 5264

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();

});
 }

Upvotes: -1

Quentin
Quentin

Reputation: 943561

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.

Upvotes: 40

Related Questions