Sending Post Request using Fetch API
Fetch API is a modern JavaScript API that allows you to make HTTP requests in a more efficient and easier way than the traditional XMLHttpRequest object. It provides a simple and intuitive way to send HTTP requests and handle responses. In this article, we will learn how to send a POST request using the Fetch API in JavaScript.
What is a POST Request?
A POST request is used when you want to send data to a server โ for example:
Submitting a contact form
Registering a user
Placing an order
The Fetch API makes this very easy.
Basic Syntax of Fetch API for POST
fetch('https://your-api-endpoint.com', {
method: 'POST', // Specify the request method
headers: {
'Content-Type': 'application/json' // Tell server you're sending JSON
},
body: JSON.stringify(data) // Convert JS object to JSON string
})
.then(response => response.json()) // Convert response to usable JSON
.then(result => {
console.log('Success:', result);
})
.catch(error => {
console.error('Error:', error);
});
Key Concepts
Part |
Explanation |
fetch() |
JavaScript method to make HTTP requests |
method: 'POST' |
Tells the server this is a POST (not GET) request |
headers |
Metadata about the request โ we tell it weโre sending JSON |
body |
Actual data we are sending (must be stringified) |
.then() |
Handles the response asynchronously |
.catch() |
Catches any errors, like network issues |
With async/await (cleaner syntax)
async function sendOrder() {
const order = {
name: "Alice",
item: "Pizza",
quantity: 1
};
try {
const response = await fetch('https://example.com/api/orders', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(order)
});
if (!response.ok) throw new Error("Request failed");
const data = await response.json();
console.log("Order successful:", data);
} catch (error) {
console.error("Error placing order:", error);
}
}
sendOrder();
Mini Project of Sending Request to Fake API
Takes input from a user in an HTML form
Sends that data as a POST request using the Fetch API
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Post Requests</title>
</head>
<body>
<h1>Food Order App</h1>
<form action="" id="orderform">
<input type="text" id="name" placeholder="Enter your name..." required>
<input type="text" id="order" placeholder="Enter your order..." required>
<button type="submit">Submit</button>
</form>
<script>
document.getElementById('orderform').addEventListener('submit', function(event){
event.preventDefault();
let name = document.getElementById('name').value
let order = document.getElementById('order').value
let orderdata = {
customername : name,
ordername : order
};
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(orderdata)
})
.then(response => response.json())
.then(result => {
console.log('Success:', result);
});
});
</script>
</body>
</html>