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

You can use the fetch method in JavaScript to make an HTTP request with a custom body as JSON. Here's an example:

index.tsx
const url = 'https://example.com/api/endpoint';
const data = { name: 'John', age: 30 };
fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
315 chars
13 lines

In this example, we are making a POST request to the URL https://example.com/api/endpoint with a JSON object as the request body. The fetch method accepts two parameters: the URL and an object containing request options. In the request options object, we set the method to POST, the Content-Type header to application/json, and the request body to the JSON string representation of our data using the JSON.stringify() method.

After making the request, we parse the response by calling the json() method on the response object. Finally, we log the response data to the console or catch any errors that occurred during the request.

gistlibby LogSnag