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

There are different ways to make an HTTP request with a custom body as text using JavaScript, below are the examples using the fetch and axios libraries.

Using fetch()

index.tsx
const url = 'http://example.com/api/data';
const data = "This is a custom body text";

fetch(url, {
  method: 'POST',
  body: data,
  headers: {
    'Content-Type': 'text/plain'
  }
}).then(response => {
  console.log(response);
}).catch(error => {
  console.error(error);
});
277 chars
15 lines

Using axios

index.tsx
const url = 'http://example.com/api/data';
const data = "This is a custom body text";

axios.post(url, data, {
  headers: {
    'Content-Type': 'text/plain'
  }
}).then(response => {
  console.log(response);
}).catch(error => {
  console.error(error);
});
256 chars
13 lines

In both examples, we set the Content-Type header to text/plain to indicate that the request body is a plain text.

gistlibby LogSnag