make a http request with a custom body in javascript

You can make an HTTP request with a custom body in JavaScript using the fetch API. Here's an example of how to do it:

fetch('https://example.com/api/endpoint', {
  method: 'POST',
  body: JSON.stringify({ foo: 'bar' }),
  headers: {
    'Content-Type': 'application/json'
  }
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error))
273 chars
11 lines

In this example, we're making a POST request to https://example.com/api/endpoint with a JSON payload of { "foo": "bar" }. The Content-Type header is set to application/json, indicating that the request body is in JSON format.

The fetch function returns a Promise that resolves with the response object. We can then use the json method of the response object to extract the response data in JSON format. If there's an error during the request, we can catch it with a catch block.

gistlibby LogSnag