To send JSON data in an HTTP request in JavaScript, you need to properly set the Content-Type
header and serialize your JSON data before sending it. Here’s how you can do it using both the XMLHttpRequest
object and the fetch
API:
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 code above, we set the Content-Type
header to application/json
using the setRequestHeader
method. Then, we use JSON.stringify
to serialize our JSON data (data
object) into a string, which we pass as the request payload 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 code above, we use the fetch
function and provide an options object as the second parameter. In the options object, we specify the request method as POST
, set the Content-Type
header to application/json
, and use JSON.stringify
to serialize the JSON data (name
and age
properties) into a string. The serialized JSON data is then passed as the body
property in the options object.
Both methods allow you to send JSON data in an HTTP request. Make sure to set the Content-Type
header appropriately and serialize your JSON data before sending it.