const apiUrl = 'https://api.example.com/data';
const requestData = {
name: 'John Doe',
age: 30,
};
// Send a POST request using fetch
fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json', // Specify JSON content type
},
body: JSON.stringify(requestData), // Convert data to JSON string
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
console.log('Success:', data); // Handle successful response
})
.catch(error => {
console.error('Error:', error); // Handle errors
});
code
POST Request with Fetch API and JSON Data
This JavaScript snippet demonstrates sending a POST request using the Fetch API. It includes headers, JSON-formatted body data, and proper error handling to manage both network and server-side issues.
Error Handling
Fetch API
POST request
JSON data
API integration
Data submission
HTTP request
Front-end development