JAVASCRIPT
Performing a POST Request with JSON Data
Learn to send data to an API using an HTTP POST request with a JSON payload, a fundamental operation for creating or updating resources in web services.
async function createResource(url, data) {
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json' // Indicate expected response type
},
body: JSON.stringify(data)
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: response.statusText }));
throw new Error(`Failed to create resource. Status: ${response.status}, Message: ${errorData.message}`);
}
// Typically, POST requests return the newly created resource or a success message
const responseData = await response.json();
console.log('Resource created successfully:', responseData);
return responseData;
} catch (error) {
console.error('Error creating resource:', error.message);
throw error;
}
}
// Example Usage:
// const newPost = {
// title: 'My New Awesome Post',
// body: 'This is the content of my new post.',
// userId: 1
// };
// createResource('https://jsonplaceholder.typicode.com/posts', newPost)
// .then(data => console.log('Created Post:', data))
// .catch(error => console.error('Error creating post:', error));
// // For file uploads, use FormData instead of JSON.stringify and omit Content-Type header
// async function uploadFile(url, file) {
// const formData = new FormData();
// formData.append('file', file);
// // Add other fields if needed: formData.append('name', 'My Document');
// const response = await fetch(url, {
// method: 'POST',
// body: formData // fetch automatically sets 'Content-Type: multipart/form-data'
// });
// return response.json();
// }
// // Example: uploadFile('/api/upload', myFileObject);
How it works: This snippet illustrates how to perform an HTTP POST request using JavaScript's `fetch` API to send JSON data to a server. It sets the `Content-Type` header to `application/json` and stringifies the data object for the request `body`. The snippet also includes error handling for non-successful responses and provides a commented example for uploading files using `FormData`, a common alternative for POST requests.