HTTP client – axios

Now, let's work on the last step, which is to use an HTTP client to communicate with the backend. We will use axios (https://github.com/axios/axios) for its simple promise-based API. Let's download it from CDN (https://unpkg.com/axios/dist/axios.min.js) and put it under the resources/static/ directory. The version we use here is v0.18.0.

Once the messages page (https://localhost:8080/messages) is opened, in order to show the existing messages as soon as possible, we will need to add the logic of retrieving messages to the created() life cycle hook of the Vue instance. And we will also need to modify the addMessage() method.

Here are the changes to the index.html file:

...
<body>
...
<script src="../axios.v0.18.0.min.js"></script>
<script type="module">
window.vm = new Vue({
...
created () {
axios.get('api/messages?_=' + new Date().getTime())
.then((response) => {
this.messages = response.data
})
...
},
methods: {
addMessage (event) {
if (!this.newMessage) return
axios.post('api/messages', {text: this.newMessage})
.then((response) => {
this.messages.push(response.data)
this.newMessage = ''
})
...
}
}
})
</script>
</body>
...

As you can see, inside the created() hook, we use axios.get() to send the retrieve message GET request. The appended ?_ parameter in the URL is designed to make the browser not use a previously cached response. Once the request completes, the message JSON data is passed in the data property of the response parameter.

In the addMessage() method, we use axios.post() to send a new message to the backend. Once the request completes, we add the saved message to the messages list.

By now, we have completed the integration in terms of getting messages and saving new messages. The deleting message logic is left as an exercise for you.

If you restart the application and open http://localhost:8080/messages, you will see those messages you previously added showing up on the page.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.237.164