javascript
error-handling fetch-api post-request json-data api-integration data-submission web-development http-request front-end-development
Published on January 26, 2024By DeveloperBreeze
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
});
Comments
Please log in to leave a comment.