JAVASCRIPT
Sending JSON Data to a REST API using POST Request
Discover how to perform a POST request with the Fetch API to send JSON data to a server. This snippet covers setting headers, stringifying the body, and handling responses.
async function postJsonData(url, dataToSend) {
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(dataToSend)
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(`HTTP error! Status: ${response.status}. Details: ${errorData.message || JSON.stringify(errorData)}`);
}
const responseData = await response.json();
console.log('Success:', responseData);
return responseData;
} catch (error) {
console.error('Error during POST request:', error);
throw error; // Re-throw to allow further handling
}
}
// Example Usage:
// const postData = {
// title: 'foo',
// body: 'bar',
// userId: 1,
// };
// postJsonData('https://jsonplaceholder.typicode.com/posts', postData)
// .then(data => console.log('Posted Data:', data))
// .catch(err => console.error('Failed to post:', err));
How it works: This snippet illustrates how to send JSON data to a REST API using an HTTP POST request with the JavaScript Fetch API. It correctly sets the `Content-Type` header to `application/json` and stringifies the JavaScript object to be sent in the request body. The function also includes robust error handling, parsing potential error messages from the server response.