To make a POST request in JavaScript, you can use the fetch() method or the XMLHttpRequest object.
Here's an example using fetch():
fetch('https://example.com/api/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'John Smith',
email: 'john@smith.com'
})
})
.then(response => response.json())
.then(data => console.log(data));
And here's an example using XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://example.com/api/create', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function () {
if (this.status === 200) {
console.log(this.response);
}
};
xhr.send(JSON.stringify({
name: 'John Smith',
email: 'john@smith.com'
}));
Top comments (0)