Skip to main content

POST Request

Overview

The snippet demonstrates how to make a POST request using the Fetch API in JavaScript. This method is commonly used to send data to a server to create or update resources. The Fetch API provides a more modern and flexible approach for making asynchronous HTTP requests in JavaScript, enhancing interaction with web services and server data retrieval.

Code

function sendPostRequest(apiUrl, requestData) {
fetch(apiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(requestData),
})
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json(); // Parse the response as JSON
})
.then((data) => {
console.log("Data received:", data);
})
.catch((error) => {
console.error("Fetch error:", error);
});
}

Example Usage

// Example data to send in the POST request
const exampleData = {
name: "Jane Doe",
email: "janedoe@example.com",
};

// Call the function with the URL and data
sendPostRequest("https://api.example.com/data", exampleData);

Code Description

The sendPostRequest function is a JavaScript function designed for making HTTP POST requests using the Fetch API. Here's a breakdown of its functionality:

Function Parameters:

  • apiUrl: A string representing the URL to which the POST request is sent.
  • requestData: An object containing the data to be sent in the request. This data is in a format suitable for JSON encoding.

Fetch API Configuration:

  • Initiates a fetch request to the apiUrl.
  • Sets the request method to "POST".
  • Includes headers indicating that the content type is application/json.
  • Stringifies the requestData into JSON format for the request body.

Response Handling:

  • Checks the response status. Throws an error for non-OK responses.
  • Parses the response body as JSON for OK responses.

Data Processing:

  • Handles the JSON data received from the server, such as logging it to the console.

Error Handling:

  • Catches and logs any errors during the fetch process, like network issues or request configuration problems.

This function is reusable and adaptable for different web applications requiring POST requests, such as form submissions or API interactions.

References