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.

Continue Reading:

Simple Server-Side Handling of HTTP Methods

Published on January 26, 2024

php

File Upload

Published on January 26, 2024

php

Asynchronous Data Fetching in JavaScript using 'fetch'

Published on January 26, 2024

javascript

Asynchronous Fetch in JavaScript using async/await

Published on January 26, 2024

javascript

JavaScript File Upload using Fetch API and FormData

Published on January 26, 2024

javascript

Fetch JSON Data from API in JavaScript

Published on January 26, 2024

javascript

Fetching Chuck Norris Jokes from API in JavaScript

Published on January 26, 2024

javascript

Tailwind Browser Mockup

Published on January 26, 2024

Simple and Clean Tailwind Buttons

Published on January 26, 2024

Tailwind Buttons with Arrow Icon

Published on January 26, 2024