make a http request with a custom body as binary in javascript

To make a HTTP request with a custom binary body in JavaScript, you can use either the XMLHttpRequest (XHR) object or the newer Fetch API. Here's how you can do it with both approaches:

Using XMLHttpRequest (XHR):

index.tsx
const httpRequest = new XMLHttpRequest();
const url = "https://example.com/api/upload";
const binaryData = new ArrayBuffer(8); // replace with your own binary data

httpRequest.onreadystatechange = () => {
  if (httpRequest.readyState === XMLHttpRequest.DONE) {
    if (httpRequest.status === 200) {
      console.log(httpRequest.responseText);
    } else {
      console.log("Error!", httpRequest.status);
    }
  }
};
httpRequest.open("POST", url);
httpRequest.setRequestHeader("Content-Type", "application/octet-stream"); // set the content type as "application/octet-stream"
httpRequest.send(binaryData);
609 chars
17 lines

Using Fetch:

index.tsx
const url = "https://example.com/api/upload";
const binaryData = new ArrayBuffer(8); // replace with your own binary data

fetch(url, {
  method: "POST",
  body: binaryData,
  headers: {
    "Content-Type": "application/octet-stream" // set the content type as "application/octet-stream"
  }
})
  .then(response => {
    if (response.ok) {
      return response.text();
    } else {
      throw new Error("Error!", response.status);
    }
  })
  .then(body => console.log(body))
  .catch(error => console.error(error));
520 chars
20 lines

In both cases, replace url with your own API URL and binaryData with your own binary data.

gistlibby LogSnag