如何在XMLHttpRequest asyn中设置多个标头数据

时间:2018-07-02 09:23:57

标签: javascript xmlhttprequest http-headers

我的api调用要求我在标头中传递api密钥,但是我从api服务{"error":"2424452","message":"Invalid Api Key"}中回来了错误

我知道我的api密钥有效,因为我可以在Python中进行相同的api调用,例如:

req = requests.Session()
req.headers.update({'x-api-key': 'my-api-key', 'X-Product': 'my-product-name'})
req.get(url)

但是在javscript中,相同的调用会出错。我相信我没有正确设置标题或其他内容?

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不是浏览器调用,而是在支持XMLHttpRequest的应用程序中

3 个答案:

答案 0 :(得分:9)

<AssemblyName Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">MyExe_Debug_x86</AssemblyName> <AssemblyName Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">MyExe_Release_x86</AssemblyName> <AssemblyName Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">MyExe_Debug_x64</AssemblyName> <AssemblyName Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">MyExe_Release_x64</AssemblyName> 设置一个标头,并使用两个自变量(名称和值)。

如果要设置多个标题,请多次调用setRequestHeader。不要在第一个调用中添加额外的参数。

答案 1 :(得分:2)

如果您不想显式设置多个标题

function setHeaders(headers){
  for(let key in headers){
    xhr.setRequestHeader(key, header[key]) 
  }
}
setHeaders({"Host":"api.domain.com","X-Requested-With":"XMLHttpRequest","contentType":"application/json"})

答案 2 :(得分:-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();

});
 }