To make a POST request in JavaScript, you can use either the XMLHttpRequest
object or the fetch
API. I’ll provide examples for both methods:
Using XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/data', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
}
};
var data = {
name: 'John Doe',
age: 25
};
xhr.send(JSON.stringify(data));
In the above code, we create a new XMLHttpRequest
object, set the request method to ‘POST’, specify the URL, set the ‘Content-Type’ header to ‘application/json’ (assuming we are sending JSON data), define an onreadystatechange
callback to handle the response, serialize the data as JSON using JSON.stringify
, and send the request using the send
method.
Using the fetch API:
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'John Doe',
age: 25
})
})
.then(function(response) {
if (response.ok) {
return response.json();
}
throw new Error('Network response was not OK.');
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log('Error:', error.message);
});
In the above code, we use the fetch
function with the URL and an options object. In the options object, we specify the request method as ‘POST’, set the ‘Content-Type’ header to ‘application/json’, and provide the request body as a serialized JSON string using JSON.stringify
.
Both methods allow you to customize the request headers and body based on your needs.