Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Vue Communicates with the Internet Chapter 14

Processing a request before sending it out


This recipe teaches you how to use interceptors to edit your request before it goes out to the


Internet. This can be useful in some cases, such as when you need to supply an
authorization token along with all the requests to your server or when you need a single


point to edit how your API calls are performed.


Getting ready


This recipe uses Axios (the Sending basic AJAX requests with Axios recipe); apart from that, it
will be useful to have completed the How to validate user data before sending it recipe since we


will build a small form for demonstration.


How to do it...


In this recipe, you will build a filter for curse words for a hypothetical comment system.
Suppose there's an article on our website that can potentially start a flame war:


<div id="app">
<h3>Who's better: Socrates or Plato?</h3>
<p>Technically, without Plato we wouldn't have<br>
much to go on when it comes to information about<br>
Socrates. Plato ftw!</p>

After that article, we place a comment box:


<form>
<label>Write your comment:</label>
<textarea v-model="message"></textarea>
<button @click.prevent="submit">Send!</button>
</form>
<p>Server got: {{response}}</p>
</div>

We also added a line after the form to debug the response that we will get from the server.

Free download pdf