Update httpGet.md
This commit is contained in:
@ -2,20 +2,28 @@
|
|||||||
|
|
||||||
Makes a `GET` request to the passed URL.
|
Makes a `GET` request to the passed URL.
|
||||||
|
|
||||||
Use `XMLHttpRequest` web api to make a `get` request to the given `url`.
|
Use [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest) web api to make a `get` request to the given `url`.
|
||||||
Handle the `onload` event, by console logging the `responseText`.
|
Handle the `onload` event, by calling the given `callback` the `responseText`.
|
||||||
Handle the `onerror` event, by running the provided `err` function.
|
Handle the `onerror` event, by running the provided `err` function.
|
||||||
|
Omit the third argument, `err`, to log errors to the console's `error` stream by default.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const httpGet = (url, err = console.error) => {
|
const httpGet = (url, callback, err = console.error) => {
|
||||||
const request = new XMLHttpRequest();
|
const request = new XMLHttpRequest();
|
||||||
request.open("GET", url, true);
|
request.open("GET", url, true);
|
||||||
request.onload = () => console.log(request.responseText);
|
request.onload = () => callback(request.responseText);
|
||||||
request.onerror = () => err(request);
|
request.onerror = () => err(request);
|
||||||
request.send();
|
request.send();
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
httpGet('https://jsonplaceholder.typicode.com/posts'); // 'Console logs JSON of 100 posts'
|
httpGet('https://jsonplaceholder.typicode.com/posts/1', console.log); /*
|
||||||
|
Logs: {
|
||||||
|
"userId": 1,
|
||||||
|
"id": 1,
|
||||||
|
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
|
||||||
|
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
|
||||||
|
}
|
||||||
|
*/
|
||||||
```
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user