Vue Communicates with the Internet Chapter 14
How it works...
Most of the magic happens in the submit method. In the first line, we are creating an
XMLHttpRequest object, which is a native JavaScript mechanism to make AJAX requests:
const xhr = new XMLHttpRequest()
We then use the open and setRequestHeader methods to configure a new connection; we
want to send a POST request, and we will send some JSON along with it:
xhr.open('post', 'http://jsonplaceholder.typicode.com/posts')
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
Since we are interacting with a RESTful interface, the POST method means that we expect
our request to modify data on the server (in particular, create a new post), and that issuing
the same request more than one time will get different results every time (namely we will
create a new, different post ID each time).
This is different from the more common GET request that will not modify data on the
server (except logs maybe) and this will always yield the same results (provided that data
on the server does not change between requests).
For more details about REST, take a look at the Creating a REST client (and server!) recipe.
The following lines are all about the response:
xhr.onreadystatechange = () => {
const DONE = 4
const CREATED = 201
if (xhr.readyState === DONE) {
if (xhr.status === CREATED) {
this.response = xhr.response
} else {
this.response = 'Error: ' + xhr.status
}
}
}
This will install a handler whenever we get some kind of change in our object. If the
readyState is changed to DONE it means, that we have our response from the server. Next,
we check the status code, which should be 201 to signal that a new resource (our new post)
has been created. If that is the case, we set the variable we put in the mustaches to get a
quick feedback. Otherwise, we put the error message we received in the same variable.