Reader small image

You're reading from  Vue.js 2 Cookbook

Product typeBook
Published inApr 2017
Reading LevelBeginner
PublisherPackt
ISBN-139781786468093
Edition1st Edition
Languages
Right arrow
Author (1)
Andrea Passaglia
Andrea Passaglia
author image
Andrea Passaglia

Andrea Passaglia was born in Genoa, in northern Italy. Interested about technology since his parents gave him a toy computer when he was a boy, he started studying web technologies at an early age. After obtaining his master's degree in computer engineering he worked on the design and implementation of web interfaces for companies of various sizes and in different industries (healthcare, fashion, tourism, and transport). In 2016 he moves in the silicon valley of Europe to tackle new problems in the banking industry at the Edgeverve Dublin Research and Development Labs. A backend technologist by trade, Vue.js is his first tool to bring to life his creations when it comes to the frontend. Andrea is married to a lovely Russian girl from Siberia and they often cook together mixing culinary traditions.
Read more about Andrea Passaglia

Right arrow

Chapter 5. Vue Communicates with the Internet

In this chapter, the following recipes will be covered:

  • Sending basic AJAX request with Axios
  • Validating user data before sending it
  • Creating a form and sending data to your server
  • Recovering from an error during a request
  • Creating a REST client (and server!)
  • Implementing infinite scrolling
  • Processing a request before sending it out
  • Preventing XSS attacks to your app

Introduction


Web applications rarely work all by themselves. What makes them interesting is actually the fact that they enable us to communicate with the world in innovative ways that didn't exist just a few years ago.

Vue, by itself, doesn't contain any mechanism or library to make AJAX requests or open web sockets. In this chapter, we will, therefore, explore how Vue interacts with built-in mechanisms and external libraries to connect to external services.

You will start by making basic AJAX requests with the help of an external library. Then, you'll explore some common patterns with sending and getting data in forms. Finally, there are some recipes with real-world applications and how to build a RESTful client.

Sending basic AJAX requests with Axios


Axios is the recommended library for Vue for making HTTP requests. It's a very simple library, but it has some built-in features that help you in carrying out common operations. It implements a REST pattern for making requests with HTTP verbs and can also deal with concurrency (spawning multiple requests at the same time) in a function call. You can find more information at https://github.com/mzabriskie/axios.

Getting ready

For this recipe, you don't need any particular knowledge of Vue. We will use Axios, which itself uses JavaScript promises. If you have never heard of promises, you can have a primer at https://developers.google.com/web/fundamentals/getting-started/primers/promises.

How to do it...

You will build a simple application that gives you a wise piece of advice every time you visit the web page.

The first thing you will need is to install Axios in your application. If you are using npm, you can just issue the following command:

npm install axios...

Validating user data before sending it


Generally, users hate forms. While we can't do much to change that, we can make it less frustrating for them by providing relevant instructions on how to fill them in. In this recipe, we will create a form, and we will leverage HTML standards to provide the user with a nice guidance on how to complete it.

Getting ready

This recipe does not need previous knowledge to be completed. While we will build a form (the Sending basic AJAX requests with Axios recipe), we will fake the AJAX call and concentrate on the validation.

How to do it...

We will build a very simple form: one field for the username and one for the user e-mail, plus one button to submit the information.

Type in this HTML:

<div id="app"> 
  <form @submit.prevent="vueSubmit"> 
    <div> 
      <label>Name</label> 
      <input type="text" required> 
    </div> 
    <div> 
      <label>Email</label> 
      <input type="email" required...

Creating a form and sending data to your server


HTML forms are a standard way to interact with your user. You can gather their data to register within the site, make them log in, or even carry out more advanced interactions. In this recipe, you will build your first form with Vue.

Getting ready

This recipe is very easy, but it assumes that you already know about AJAX and you want to apply your knowledge on Vue.

How to do it...

Let's pretend that we have a blog, and we want to write a new post. For that, we need a form. Here is how you lay out the HTML:

<div id="app"> 
  <h3>Write a new post</h3> 
  <form> 
    <div> 
      <label>Title of your post:</label> 
      <input type="text" v-model="title"> 
    </div> 
    <div> 
      <label>Write your thoughts for the day</label> 
      <textarea v-model="body"></textarea> 
    </div> 
    <div> 
      <button @click.prevent="submit">Submit</button...

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 flacky and it's better to come prepared in case our request does not complete successfully.

 

Getting ready

This recipe is a little complex, but, does not use advanced concepts. You are expected, nonetheless, to be familiar with using Vue.

We will be using Axios for this recipe. You can complete the Sending basic AJAX requests with Axios recipe if you are unsure of what it exactly entails.

How to do it...

You will build a website for ordering pizzas on Mt. Everest. The area has notoriously poor Internet connection, so we may want to retry a couple of times before giving up on our pizza.

This is what our HTML looks like:

<div id="app">...

Creating a REST client (and server!)


In this recipe, we will learn about REST and how to build a REST client. To build a REST client, we will need a server that exposes a REST interface; we will build that also. Wait a minute! A whole REST server is a side note in a recipe in a book about Vue? Just follow along and you won't be disappointed.

 

Getting ready

This recipe is fairly advanced in the sense that you will need to be comfortable with the architecture of client and server and at least have heard or read about REST interfaces. You will also need to be familiar with the command line and have npm installed. You can read all about it in the Choosing a development environment recipe.

Axios will also need to be installed; read more about this in the first recipe of this chapter.

How to do it...

I remember when some years ago, building a REST server could take days or weeks. You can use Feather.js, and it will be quick and (hopefully painless). Open a command line and install it through npm with...

Implementing infinite scrolling


Infinite scrolling is a fine example of what you can do with Vue and AJAX. It is also quite popular and can improve interaction for some kind of content. You will build a random word generator that works with infinite scrolling.

Getting ready

We will use Axios. Take a look at the Sending basic AJAX requests with Axios recipe to know how to install it and its basic functionality. Other than that, you don't need to know much to follow along.

How to do it...

To make our app work, we will ask random words from the http://www.setgetgo.com/randomword/get.php endpoint. Every time you point the browser at this address, you will get a random word.

The whole page will consist solely of an infinite list of words. Write the following HTML:

<div id="app"> 
  <p v-for="word in words">{{word}}</p> 
</div>

The list of words needs to grow as we scroll down. So we need two things: understanding when the user reaches the bottom of the page, and getting new words...

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...

Preventing XSS attacks to your app


Writing applications without thinking about security will inevitably lead to vulnerabilities, especially if it has to run on a web server. Cross site scripting (XSS) is among the most popular security issues nowadays; even if you are not a security expert, you should be aware of how it works and how to prevent it in a Vue application.

 

Getting ready

This recipe does not need any previous knowledge except for Axios. You can find more on Axios and how to install it in the Sending basic AJAX requests with Axios recipe.

How to do it...

The first thing you should do is to discover how your backend is giving you the CSRF token (more on this in the next paragraph). We will suppose that the server will place a cookie in your browser with the name, XSRF-TOKEN.

Note

You can simulate your server, setting a cookie with the document.cookie = 'XSRF-TOKEN=abc123' command issued in the browser console (in the developer tools).

Axios automatically reads such a cookie and transmits...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Vue.js 2 Cookbook
Published in: Apr 2017Publisher: PacktISBN-13: 9781786468093
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Andrea Passaglia

Andrea Passaglia was born in Genoa, in northern Italy. Interested about technology since his parents gave him a toy computer when he was a boy, he started studying web technologies at an early age. After obtaining his master's degree in computer engineering he worked on the design and implementation of web interfaces for companies of various sizes and in different industries (healthcare, fashion, tourism, and transport). In 2016 he moves in the silicon valley of Europe to tackle new problems in the banking industry at the Edgeverve Dublin Research and Development Labs. A backend technologist by trade, Vue.js is his first tool to bring to life his creations when it comes to the frontend. Andrea is married to a lovely Russian girl from Siberia and they often cook together mixing culinary traditions.
Read more about Andrea Passaglia