JAVASCRIPT
Sending JSON Data with a POST Request in JavaScript
Master sending data to APIs using JavaScript's Fetch API with a POST request, including how to correctly set headers and serialize a JSON body.
async function postData(url, payload) {
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
// 'Authorization': 'Bearer YOUR_AUTH_TOKEN' // Add if authentication is required
},
body: JSON.stringify(payload)
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(`HTTP error! Status: ${response.status}, Message: ${errorData.message || response.statusText}`);
}
const data = await response.json();
console.log('Data posted successfully:', data);
return data;
} catch (error) {
console.error('Error posting data:', error.message);
throw error;
}
}
// Example usage:
// const apiUrl = 'https://api.example.com/create-resource';
// const newResource = { name: 'New Item', value: 123 };
// postData(apiUrl, newResource)
// .then(data => console.log('Resource created:', data))
// .catch(err => console.error('Failed to create resource:', err));
How it works: This snippet illustrates how to send data to an API endpoint using a POST request with JavaScript's `fetch` API. It correctly sets the `Content-Type` header to `application/json` and serializes the JavaScript object `payload` into a JSON string for the request body. Robust error handling for HTTP responses is also included, making the integration more reliable.