Vue Communicates with the Internet Chapter 14
The last thing we need to do, after setting up the event handlers, is to actually send the
request along with the data of our new post:
xhr.send(JSON.stringify({
title: this.title,
body: this.body,
userId: this.userId
}))
There's more...
Another way to approach the same problem is to use Axios for sending the AJAX request. If
you need to brush up on what Axios is, take a look at the Sending basic AJAX requests with
Axios recipe.
The code for the submit method will become as follows (remember to add Axios as a
dependency):
submit () {
axios.post('http://jsonplaceholder.typicode.com/posts', {
title: this.title,
body: this.body,
userId: this.userId
}).then(response => {
this.response = JSON.stringify(response,null,' ')
}).catch(error => {
this.response = 'Error: ' + error.response.status
})
}
This code is perfectly equivalent, but it's much more expressive and concise than using
native browser objects.
Recovering from an error during a request
Requests to an external service take ages from the perspective of a computer. In human
terms, it would be like sending a satellite to Jupiter and waiting for it to come back to Earth.
You can't be 100% sure that the travel will ever be complete and how much time will the
travel actually take. Networks are notoriously flaky and it's better to come prepared in case
our request does not complete successfully.