JAVASCRIPT
Sending Data to an API with POST Request (JSON)
Discover how to send JSON data to a REST API using JavaScript's `fetch` API for POST requests, ensuring proper content type headers and request body formatting.
async function postDataToAPI(url, data) {
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const responseData = await response.json();
console.log('Data posted successfully:', responseData);
return responseData;
} catch (error) {
console.error('Error posting data:', error);
return null;
}
}
// Usage example:
// const newData = { name: 'John Doe', email: '[email protected]' };
// postDataToAPI('https://api.example.com/users', newData)
// .then(result => {
// if (result) {
// console.log('User created with ID:', result.id);
// }
// });
How it works: This code snippet shows how to make a POST request to an API endpoint using the `fetch` API. It correctly sets the `Content-Type` header to `application/json` and stringifies the JavaScript object to be sent as the request body. It also includes error handling and parses the API's JSON response, which is crucial for creating or updating resources.