Lei Zhao Lei Zhao - 4 months ago 21
Javascript Question

How do I POST raw JSON data without using AJAX?

I have an API endpoint that I want to call. It seems an easy task but to my surprise, it isn't. Here's why:


  • I can't use AJAX because the response of this API is a file to download. So I probably need to create a hidden iframe and send regular POST request from there.

  • I need to POST data as a raw JSON string, not in form data. The API does not accept key value pairs. So I can't just create an HTML form and submit it.

  • This is not my API. I can't change it.



Now I'm stuck. Is there anything else I can try?

Answer

You could do that with ajax or raw XMLHttpRequest()

A few things already mentioned in the commments to your question that explain what's going on here.

First you need a request object. Posting is no problemo, you'll pass the JSON payload you've gotta send on that last line there. After the POST is successful you'll need to take the binary returned and make an Blob for the correct file type, an objecctUrl and finally a hidden link that you'll click for the user. Please note the download attribute. This lets modern browsers know it's a download link which let's the download roll.

I've probably got some of this code from stackoverflow...

  const xlsx = {};
  const xhr = new XMLHttpRequest();
  xhr.open('POST', '/data/some.ashx');
  xhr.responseType = 'blob';
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.onload = function loadXLXS() {
    let objectUrl;
    if (this.status === 200) {
       blob = this.response
       csvURL = window.URL.createObjectURL(blob);
       tempLink = document.createElement('a');
       tempLink.href = csvURL;
       tempLink.setAttribute('download', workBookName);
       tempLink.click();
    }
  };
  xhr.send(JSON.stringify(xlsx));