add httpPost, update examples for http snippets

This commit is contained in:
Stefan Feješ
2018-01-08 21:07:02 +01:00
parent ad4a203604
commit ff00c50e5f
2 changed files with 34 additions and 3 deletions

View File

@ -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'
```

31
snippets/httpPost.md Normal file
View File

@ -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'
```