make a http request with a custom body as json and return a json response in typescript

To make an HTTP request with a custom body as JSON and return a JSON response in TypeScript, you can use the fetch method which is natively provided by the browser. Here's an example:

index.ts
interface MyData {
  // Define the structure of the data you want to send
  // In this case, we'll just define a simple message property
  message: string;
}

const postData = async (url: string, data: MyData): Promise<any> => {
  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  });
  return await response.json();
};

// Usage example
const myData: MyData = { message: "Hello server!" };
const url = "https://api.example.com/my-endpoint";
const response = await postData(url, myData);
console.log(response);
615 chars
23 lines

In this example, we define an interface called MyData which represents the data structure that we want to send to the server. We then define a function called postData which takes a URL and an instance of MyData as arguments, and returns a Promise which resolves to the JSON response.

Inside the function, we use the fetch method to make a POST request to the server. We set the request headers to specify that we're sending JSON data, and we also specify the request body as a JSON string using JSON.stringify.

Once the server responds, we parse the JSON response using response.json(), and return the parsed JSON object.

To use this function, we simply call postData with a URL and an instance of MyData, and await the Promise that it returns. The response will be logged to the console in this example, but you would typically do something more useful with it in a real-world scenario.

gistlibby LogSnag