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

To make an HTTP request with a custom body as JSON in TypeScript, you can use the built-in fetch method with the POST method and the appropriate headers set. Here's an example:

index.ts
const data = {
    name: "John",
    age: 30
};

fetch('https://example.com/api', {
    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));
310 chars
16 lines

In this example, we first create an object data that we want to send as the JSON payload. We then use the fetch method with the POST method and set the Content-Type header to application/json. We then stringify the data object and set it as the body of the request.

After that, we handle the response by calling response.json() to parse the JSON response and log it to the console. If there's an error, we catch it and log the error to the console.

This code assumes that the API expects a JSON payload and that it will return a JSON response. If your API expects a different payload or returns a different response format, you'll need to adjust the code accordingly.

related categories

gistlibby LogSnag