Changing the World on the Server
To create new data (like a comment or user), send it in the request body.
async function createPost(title, body) {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ title, body, userId: 1 })
});
const newPost = await response.json();
console.log('Created:', newPost.id); // Server assigns an ID
return newPost;
}
Updating Data (PATCH / PUT)
// PATCH — partial update (only fields you provide change)
await fetch('/api/users/42', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: 'new@email.com' }) // Only email changes
});
// PUT — full replacement (all fields must be provided)
await fetch('/api/users/42', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Alice', email: 'alice@example.com', age: 28 })
});
Important
When sending JSON, always include the header Content-Type: application/json. Without it, the server may not know how to parse the request body.