httpPost
Makes a POST request to the passed URL.
- Use the
XMLHttpRequestweb API to make aPOSTrequest to the givenurl. - Set the value of an
HTTPrequest header withsetRequestHeadermethod. - Handle the
onloadevent, by calling the givencallbacktheresponseText. - Handle the
onerrorevent, by running the providederrfunction. - Omit the fourth argument,
err, to log errors to the console'serrorstream by default.
const httpPost = (url, data, callback, err = console.error) => {
const request = new XMLHttpRequest();
request.open('POST', url, true);
request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
request.onload = () => callback(request.responseText);
request.onerror = () => err(request);
request.send(data);
};
const newPost = {
userId: 1,
id: 1337,
title: 'Foo',
body: 'bar bar bar'
};
const data = JSON.stringify(newPost);
httpPost(
'https://jsonplaceholder.typicode.com/posts',
data,
console.log
); /*
Logs: {
"userId": 1,
"id": 1337,
"title": "Foo",
"body": "bar bar bar"
}
*/
httpPost(
'https://jsonplaceholder.typicode.com/posts',
null, // does not send a body
console.log
); /*
Logs: {
"id": 101
}
*/