DeveloperBreeze

Snippets Programming Tutorials, Guides & Best Practices

Explore 196+ expertly crafted snippets tutorials, components, and code examples. Stay productive and build faster with proven implementation strategies and design patterns from DeveloperBreeze.

POST Request with Fetch API and JSON Data

Code January 26, 2024
javascript


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
    });