make a http request with a custom body as multipart form data in javascript

Here's an example of making a HTTP request with a custom body as multipart form data using the Fetch API in JavaScript:

index.tsx
const formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

fetch('http://example.com/api/endpoint', {
  method: 'POST',
  body: formData
}).then(response => {
  console.log(response);
}).catch(error => {
  console.error(error);
});
277 chars
13 lines

Here's an example of making a HTTP request with a custom body as multipart form data using XMLHttpRequest in JavaScript:

index.tsx
const formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://example.com/api/endpoint');
xhr.onload = function() {
  console.log(xhr.responseText);
};
xhr.onerror = function() {
  console.error(xhr.statusText);
};
xhr.send(formData);
336 chars
14 lines

gistlibby LogSnag