← Back to all snippets
JAVASCRIPT

Submit Form Data to a REST API using Fetch POST Request

Discover how to securely send JSON data to a REST API endpoint using the Fetch API's POST method, including proper headers and error handling.

async function postData(url, data) {
    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
                // Add authorization headers if needed:
                // 'Authorization': `Bearer ${yourAuthToken}`
            },
            body: JSON.stringify(data)
        });

        if (!response.ok) {
            const errorData = await response.json().catch(() => ({ message: response.statusText }));
            throw new Error(`HTTP error! Status: ${response.status}, Details: ${errorData.message || 'Unknown error'}`);
        }

        const responseData = await response.json();
        return responseData;
    } catch (error) {
        console.error("Error posting data:", error);
        throw error;
    }
}

// Example usage:
async function createUser(userData) {
    try {
        const newUser = await postData('https://api.example.com/users', userData);
        console.log('New user created:', newUser);
    } catch (error) {
        console.error('Failed to create user:', error.message);
    }
}

// Call the example function with dummy data
// createUser({ name: 'John Doe', email: '[email protected]' });
How it works: This snippet illustrates how to send data to a REST API using a POST request with the Fetch API. It correctly sets the `Content-Type` header to `application/json` and serializes the JavaScript object into a JSON string for the request body. Robust error handling is included to catch both network issues and HTTP error statuses, providing informative feedback on failed submissions.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs