Files
30-seconds-of-code/snippets/httpPost.md
30secondsofcode 9b57ac1bc3 Travis build: 1168
2018-01-11 08:59:40 +00:00

1.2 KiB

httpPost

Makes a POST request to the passed URL.

Use XMLHttpRequest web api to make a post request to the given url. Set the value of an HTTP request header with setRequestHeader method. Handle the onload event, by calling the given callback the responseText. Handle the onerror event, by running the provided err function. Omit the third argument, data, to send no data to the provided url. Omit the fourth argument, err, to log errors to the console's error stream by default.

const httpPost = (url, callback, data = null, 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', console.log, data; /*
Logs: {
  "userId": 1,
  "id": 1337,
  "title": "Foo",
  "body": "bar bar bar"
}
*/