To make a POST request in JavaScript, you can use the fetch()
function or the XMLHttpRequest
object. I’ll provide examples for both approaches:
Using fetch():
javascriptCopy code// Create a JSON object with the data to be sent in the request body
var data = {
username: "john_doe",
password: "secretpassword"
};
// Make a POST request using fetch()
fetch('https://example.com/api/endpoint', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
console.log('Response:', data);
})
.catch(error => {
console.error('Error:', error);
});
In this example, we use fetch()
to make a POST request to the specified URL (https://example.com/api/endpoint
). We set the request method to 'POST'
and specify the 'Content-Type'
header as 'application/json'
since we are sending JSON data in the request body. The JSON.stringify()
method is used to convert the data
object to a JSON string before sending it in the request body.
The response from the server is parsed as JSON using the .json()
method, and we can access the response data in the subsequent then()
block. Any errors during the request are caught in the catch()
block.
Using XMLHttpRequest:
javascriptCopy code// Create a JSON object with the data to be sent in the request body
var data = {
username: "john_doe",
password: "secretpassword"
};
// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Set up the request
xhr.open('POST', 'https://example.com/api/endpoint', true);
xhr.setRequestHeader('Content-Type', 'application/json');
// Define a callback function to handle the response
xhr.onload = function() {
if (xhr.status === 200) {
var responseData = JSON.parse(xhr.responseText);
console.log('Response:', responseData);
} else {
console.error('Request failed. Status:', xhr.status);
}
};
// Handle network errors
xhr.onerror = function() {
console.error('Request failed. Network error.');
};
// Send the request with the JSON data in the request body
xhr.send(JSON.stringify(data));
In this example, we create an XMLHttpRequest
object using new XMLHttpRequest()
and set up the request using the open()
method. We specify the request method as 'POST'
and set the 'Content-Type'
header as 'application/json'
.
We define an onload
callback function that is executed when the response is received. If the status code is 200
(indicating a successful response), we parse the response data using JSON.parse()
and log it to the console. Otherwise, we log an error message with the corresponding status code.
The onerror
callback function is triggered if there is a network error during the request.
The JSON data is sent in the request body using the send()
method, after converting it to a JSON string with JSON.stringify()
.

Brijpal Sharma is a web developer with a passion for writing tech tutorials. Learn JavaScript and other web development technology.