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.ts615 chars23 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