Update httpPost.md
This commit is contained in:
@ -2,29 +2,38 @@
|
|||||||
|
|
||||||
Makes a `POST` request to the passed URL.
|
Makes a `POST` request to the passed URL.
|
||||||
|
|
||||||
Use `XMLHttpRequest` web api to make a `post` request to the given `url`.
|
Use [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest) web api to make a `post` request to the given `url`.
|
||||||
Set the value of an `HTTP` request header with `setRequestHeader` method.
|
Set the value of an `HTTP` request header with `setRequestHeader` method.
|
||||||
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, `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.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const httpPost = (url, data, err = console.error) => {
|
const httpPost = (url, callback, data = null, err = console.error) => {
|
||||||
const request = new XMLHttpRequest();
|
const request = new XMLHttpRequest();
|
||||||
request.open("POST", url, true);
|
request.open("POST", url, true);
|
||||||
request.setRequestHeader('Content-type','application/json; charset=utf-8');
|
request.setRequestHeader('Content-type','application/json; charset=utf-8');
|
||||||
request.onload = () => console.log(request.responseText);
|
request.onload = () => callback(request.responseText);
|
||||||
request.onerror = () => err(request);
|
request.onerror = () => err(request);
|
||||||
request.send(data);
|
request.send(data);
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const user = {
|
const newPost = {
|
||||||
name: "Foo",
|
"userId": 1,
|
||||||
password: "fooBar"
|
"id": 1337,
|
||||||
|
"title": "Foo",
|
||||||
|
"body": "bar bar bar"
|
||||||
};
|
};
|
||||||
const data = JSON.stringify(user);
|
const data = JSON.stringify(newPost);
|
||||||
httpPost('https://website.com/posts', data, request => {
|
httpPost('https://website.com/posts', console.log, data; /*
|
||||||
console.log(request.responseText);
|
Logs: {
|
||||||
}); // ''
|
"userId": 1,
|
||||||
|
"id": 1337,
|
||||||
|
"title": "Foo",
|
||||||
|
"body": "bar bar bar"
|
||||||
|
}
|
||||||
|
*/
|
||||||
```
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user