JAVASCRIPT
Send JSON Data with a POST Request using Fetch
Learn to make POST requests with JSON payloads to web APIs using the modern Fetch API in JavaScript, essential for creating or updating resources on a server.
async function postJsonData(endpoint, dataToSend) {
try {
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(dataToSend) // Convert JavaScript object to JSON string
});
if (!response.ok) {
const errorDetail = await response.json().catch(() => ({ message: 'No error message available.' }));
throw new Error(`HTTP error! Status: ${response.status}. Details: ${errorDetail.message}`);
}
const responseData = await response.json();
console.log('Successfully posted data:', responseData);
return responseData;
} catch (error) {
console.error('Failed to post JSON data:', error.message);
throw error;
}
}
// Usage example:
// const newPost = {
// title: 'My New Article',
// body: 'This is the content of my new article.',
// userId: 1
// };
//
// postJsonData('https://jsonplaceholder.typicode.com/posts', newPost)
// .then(data => console.log('Created Post:', data))
// .catch(err => console.error('Error creating post:', err.message));
How it works: This snippet shows how to perform a POST request with a JSON payload using the Fetch API. Key elements include setting the `method` to 'POST', specifying `'Content-Type': 'application/json'` in the headers, and converting the JavaScript data object into a JSON string using `JSON.stringify()` for the `body`. It also includes basic error checking for the HTTP response.