diff --git a/snippets/httpGet.md b/snippets/httpGet.md index cc8e6c1d7..1d183312c 100644 --- a/snippets/httpGet.md +++ b/snippets/httpGet.md @@ -2,7 +2,7 @@ Makes a `GET` request to the passed URL. -Use `XMLHttpRequest` web api to retrieve data from the given `url`. +Use `XMLHttpRequest` web api to make a `get` request to the given `url`. Handle the `onload` event, by running the provided `callback` function. Handle the `onerror` event, by running the provided `err` function. Omit the third argument, `err` to log the request to the console's error stream by default. @@ -18,7 +18,7 @@ const httpGet = (url, callback, err = console.error) => { ``` ```js -httpGet('https://jsonplaceholder.typicode.com/posts', request => { +httpGet('https://website.com/posts', request => { console.log(request.responseText); -}) // 'Array of 100 items' +}); // 'Retrieves all users from the database' ``` diff --git a/snippets/httpPost.md b/snippets/httpPost.md new file mode 100644 index 000000000..cb395b7c5 --- /dev/null +++ b/snippets/httpPost.md @@ -0,0 +1,31 @@ +### 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 running the provided `callback` function. +Handle the `onerror` event, by running the provided `err` function. +Omit the last argument, `err` to log the request to the console's error stream by default. + +```js +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); + request.onerror = () => err(request); + request.send(data); +} +``` + +```js +const user = { + name: "Foo", + password: "fooBar" +}; +const data = JSON.stringify(user); +httpPost('https://website.com/posts', data, request => { + console.log(request.responseText); +}); // 'Makes a new instance of user in database' +```