JAVASCRIPT
Sending JSON Data to an API with a POST Request
Discover how to make a POST request using the `fetch` API to send JSON data to a server, crucial for creating or updating resources in web applications.
async function postData(url, data) {
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
if (!response.ok) {
const errorBody = await response.json().catch(() => ({ message: 'No error body' }));
throw new Error(`HTTP error! status: ${response.status}, Details: ${JSON.stringify(errorBody)}`);
}
const responseData = await response.json();
console.log('Success:', responseData);
return responseData;
} catch (error) {
console.error('Error posting data:', error);
throw error;
}
}
// Example usage:
// const newUser = {
// name: 'John Doe',
// job: 'Developer'
// };
// postData('https://reqres.in/api/users', newUser)
// .then(data => console.log('New user created:', data))
// .catch(err => console.error('Failed to create user:', err));
How it works: This code snippet shows how to send data to an API using a POST request. It configures the `fetch` call with the `POST` method, sets the `Content-Type` header to `application/json`, and stringifies the JavaScript object into a JSON string for the request body. Robust error handling is included to catch non-OK responses and parse potential error messages from the server.