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

Making a HTTP request with a custom body as HTML in Javascript can be achieved using the built-in fetch() function or by creating an instance of XMLHttpRequest object.

Here's an example of making an HTTP POST request with a custom HTML body using the fetch() function:

index.tsx
fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'text/html'
  },
  body: '<html><head><title>Sample HTML</title></head><body><h1>Hello World!</h1></body></html>'
})
  .then(response => console.log(response))
  .catch(error => console.error(error));
265 chars
10 lines

In the above example, we specify the HTTP method as POST, set the Content-Type header to text/html, and provide the custom HTML body in the body property.

Alternatively, here's an example of making an HTTP POST request with a custom HTML body using the XMLHttpRequest object:

index.tsx
const xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.setRequestHeader('Content-Type', 'text/html');
xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    console.log(xhr.responseText);
  }
}
xhr.send('<html><head><title>Sample HTML</title></head><body><h1>Hello World!</h1></body></html>');
335 chars
10 lines

In this example, we set the HTTP method and request URL using the open() method, set the Content-Type header using the setRequestHeader() method, provide the custom HTML body using the send() method, and handle the response using the onreadystatechange property.

gistlibby LogSnag