Search code examples
javascriptpostwindow.openrequest-headers

How to add request headers as array to window.open post url in javascript?


I have code something similar.

url : /files/docuemnttype/zipfile

window.open('POST', url, '_blank',{"reporttype" : [1,2,3,4,5]});

I am trying to send the reporttype array as request header in post call with window.open.

Can some one help me how this work.

Thanks!!


Solution

  • You cannot use window.open to do POST request to the backend service, what you could do would be use fetch function

    fetch(url, {
      method: "POST",
      body: JSON.stringify({"reporttype" : [1,2,3,4,5]}),
      headers: {"Content-Type": "application/json"}
        .then(response => response.json())
        .then(data => console.log(data));
    

    You could also try using XMLHttpRequest

    var xhr = new XMLHttpRequest();
    
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4) {
        console.log(xhr.response);
      }
    }
    
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-type", "application/json");
    xhr.send(JSON.stringify({"reporttype" : [1,2,3,4,5]}));