Basic POST request

Creating data via a REST API usually involves using the HTTP POST method with the data we want to create in the request body.

Let's open up the TypeScript playground and enter the following: 

fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
body: JSON.stringify({
title: "Interesting post",
body: "This is an interesting post about ...",
userId: 1
})
})
.then(response => {
console.log(response.status);
return response.json();
})
.then(data => console.log(data));

The fetch call is largely the same as for getting data. The key difference is the second parameter, which is an options object that can contain the method and body for the request. Notice also that the body needs to be a string.

If we run the preceding code, we get a 201 and an object containing the generated post ID in the console.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.238.20