Understanding GET and POST method in Vue.js

210 VIEWS

·

Hypertext Transfer Protocol (HTTP) defines the structure of messages between web components such as browser or command-line clients, servers like apache, and proxies. It is a protocol that describes how hypertext should be transferred. It is the backbone of the internet. There are different HTTP methods and most developers get confused using the GET and POST method when consuming API in Vue.js.

In this article, I introduce Vue.js and then walk through steps for installation and setup. In two separate sections I explain what GET is and what POST is. I also provide code examples. At the end of the article I point out the differences between those two methods. 

I use the JSON API to walk through displaying the user’s data.

Prerequisites

Basic understanding and knowledge of:

  • HTML
  • CSS
  • avaScript

What is Vue.js?

Vue.js is a progressive JavaScript framework used to build interactive web interfaces. It is an open-source model–view–ViewModel front-end JavaScript framework for building user interfaces and single-page applications.

Installation and Setup

Including Script: You can include the Vue.js in our HTML using the following CDN link: 

<script src=

    "https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js">

</script>

 

Or, install using the following command vue create user-profile

Then, install the Axios module using the following command: > npm install Axios 

You can include Axios into the HTML using the following CDN code:

<script src=
   "https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js">
</script>

What is GET method?

GET is a method that requests data from another computer. You are not creating, removing, or updating any data. You are only requesting.

Enough of the talking. Let’s get into a real example.

 

Code Explanation

HTML Code: This section contains the structure of the application. You create:

  • a general <div> with an Id of app-vue
  • a second <div> with  a class of fetch-profile
  • a table that contains the list of users, id, name, username, and email
<template>

  <section>

    <div>

      <div class="fetch-profile">

        <button @click="fetchUsers" class="btn-users">Fetch Users</button>

        <h4 v-if="loading">Loading...</h4>

      </div>

      <div>

        <table class="user-table">

          <thead class="thead-bg">

            <tr>

              <th scope="col">#</th>

              <th scope="col">Name</th>

              <th scope="col">Username</th>

              <th scope="col">Email</th>

            </tr>

          </thead>

          <tbody v-for="(user, index) in users" :key="index">

            <tr>

              <th scope="row">{{ user.id }}</th>

              <td>{{ user.name }}</td>

              <td>{{ user.username }}</td>

              <td>{{ user.email }}</td>

            </tr>

          </tbody>

        </table>

      </div>

    </div>

  </section>

</template>

 

CSS Code: This section contains the font family, layout, and colors of the web page 

.fetch-profile {

  display: flex;

  justify-content: center;

  width: 90%;

  padding: 30px;

}

.thead-bg {

  background-color: rgb(221, 220, 220);

}

.btn-users {

  background-color: #000;

  border: none;

  color: white;

  padding: 15px 32px;

  text-align: center;

  text-decoration: none;

  display: inline-block;

  font-size: 16px;

}







.user-table{

  border-collapse: collapse;

  width: 100%;

}




.user-table td, .user-table th {

  border: 1px solid #ddd;

  padding: 8px;

}




.user-table tr:nth-child(even){background-color: #f2f2f2;}




.user-table tr:hover {background-color: #ddd;}




.user-table th {

  padding-top: 12px;

  padding-bottom: 12px;

  text-align: left;

  background-color: rgb(221, 220, 220);

  color: rgb(49, 49, 49);

}

 

JavaScript Code: This sections shows how to create a Vue instance with Vue function. A Vue application consists of a root Vue instance created with a new Vue. You will create:

  • a data method that returns an object – a loader that tells the users if the data is failed or fetched;
  • a method that fetches the user data

GET is a method that fetches data. So in this exercise I used the GET method to fetch the user data with Axios and then return a response that outputted the result on the homepage.

<script>

import axios from 'axios';

export default {

  name: "GetPage",

 

  data() {

    return {

      users: [],

      loading: false,

    };

  },

  methods: {

    fetchUsers() {

      this.loading = true;

      this.users = [];




      axios

        .get("https://jsonplaceholder.typicode.com/users")

        .then((response) => {

          const data = response.data; // [{}, {}]

          this.users = data;

          this.loading = false;

        });

    },

  },

};

</script>

Excellent work so far! The GET request gave you your data and displayed it on the browser. Now, let’s check out the result.

Output

GET method output

What is POST method?

The POST method updates data. It asks a computer to create a new resource and returns data about the newly-created resource. 

Next, let’s look at the code example.

Code Explanation

HTML Code: 

In this section you create a form input that collects the name, username, and email of the new user and then submits it to the table list.

<template>
  <section>
    <div>
      <form class="input-feild" @submit.prevent="handleSubmit">
        <input
          class="search-input"
          type="text"
          placeholder="Name"
          v-model="name"
        />
        <input
          class="search-input"
          v-model="userName"
          placeholder="Username"
          type="text"
        />
        <input
          class="search-input"
          v-model="email"
          placeholder="Email"
          type="text"
        />
        <button class="btn-search">Add Employee</button>
      </form>
        <p v-if="submitting">Submitting...</p>
        <p v-if="loading">Loading...</p>
    </div>
  </section>
</template>

 

CSS Code: This section contains the styling for the POST page.

<style scoped>

.search-input {

  padding: 6px;

  border: 2px solid black;

  margin-top: 8px;

  margin-right: 16px;

  font-size: 19px;

  width: 20%;

  color: black;

}

.input-feild {

  display: flex;

  justify-content: space-around;

  align-items: center;

  margin: 10px 0px;

}

.btn-search {

  background-color: #000;

  border: none;

  color: white;

  padding: 15px 32px;

  text-align: center;

  text-decoration: none;

  display: inline-block;

  font-size: 16px;

}

</style>

JavaScript Code:

In this example your data method returns an object with submitting status. This tells the users if the data is submitted or failed to submit. Next, the new user data is returned; which is name, username, and email. Then, you create a handleSubmit method that submits the user data.

POST is a method used to data. So in this exercise, you use the POST method to update the user data with Axios. This returns a response that outputs the result of your newly-added users to the user’s table list.

<script>

import axios from "axios";

export default {

  name: "PostPage",




  data() {

    return {

      users: [],

      loading: false,

      submitting: false,

      name: "",

      userName: "",

      email: "",

    };

  },

  methods: {

    handleSubmit() {

      this.submitting = true;

      axios

        .post("https://jsonplaceholder.typicode.com/users", {

          name: this.name,

          username: this.userName,

          email: this.email,

        })

        .then((response) => {

          const data = response.data;

          this.users.push(data);

          this.name = "";

          this.userName = "";

          this.email = "";

          this.submitting = false;

        });

    },

  },

};

</script>

 

Excellent! You have added a new user to  your user’s list with the POST request. Now let’s check out the result on the browser.

POST method output

Differences between the GET method and the POST method

 GET method
  • The data is visible to anyone in the URL
  • GET request remains in the browser
  • The default method for HTML form submission
  • It can only pass a limited amount of data
  • It fetches data
  • GET is better for non-secure data, like query strings in Google
  • it gets data from resource
POST method
  • The URL does not display the data
  • It does not remain in the browser history
  • Not the default method for an HTML form submission; it has to be specified
  • The POST method can only pass a large amount of data
  • It updates data
  • It posts data at a resource

Conclusion

Wow, we have come a long way. Because there are different HTTP methods, most developers get confused using the GET and POST method when consuming API in Vue.js. I hope this article has given you a good understanding of what GET and POST methods are. 


I am a software developer with development experience in frontend building responsive website sites using these web technologies like Javascript, VueJs, HTML and CSS, Bootstrap Tailwind CSS. I specialize in converting designs to Code, and I love teaching and sharing my technical ideas through an article.


Discussion

Click on a tab to select how you'd like to leave your comment

Leave a Comment

Your email address will not be published. Required fields are marked *