JAVASCRIPT
Sending JSON Data via POST Request with JavaScript Fetch
Discover how to send JSON data to a REST API using a POST request with the JavaScript Fetch API, properly setting headers and the request body.
async function postData(url, data) {
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const responseData = await response.json();
console.log('Success:', responseData);
return responseData;
} catch (error) {
console.error('Error during POST request:', error);
throw error;
}
}
// Example usage:
const newPost = {
title: 'My New Post',
body: 'This is the content of my new post.',
userId: 1
};
postData('https://jsonplaceholder.typicode.com/posts', newPost)
.then(data => console.log('New post created:', data))
.catch(err => console.error('Failed to create post:', err));
How it works: This snippet shows how to perform a POST request to an API endpoint. It correctly sets the `Content-Type` header to `application/json` and serializes the JavaScript object `data` into a JSON string for the request body. This is a fundamental pattern for sending new resources or updates to a RESTful API.