Vue.js HTTP Requests (Vue Resource, Axios)

In modern web applications, interacting with APIs to fetch or send data is a common requirement. Vue.js does not include built-in HTTP request functionality, but it seamlessly integrates with libraries like Vue Resource and Axios to handle HTTP requests.

Introduction to HTTP Requests in Vue.js

HTTP requests allow your Vue.js application to communicate with a backend server or third-party APIs. Through HTTP methods like GET, POST, PUT, and DELETE, your app can:

  • Fetch data from a server.
  • Submit form data.
  • Update or delete resources on a server.

Vue.js makes handling these operations easy by using libraries such as Vue Resource or Axios.

Vue Resource (Deprecated but still in use)

Vue Resource was the default HTTP client for Vue.js before it was deprecated in favor of Axios. It’s still used in older Vue projects and is worth understanding if you are working with legacy systems.

Installing Vue Resource

To install Vue Resource in your project, use the following command:

				
					npm install vue-resource --save
				
			

Next, you need to import and use it in your Vue project:

				
					import Vue from 'vue';
import VueResource from 'vue-resource';

Vue.use(VueResource);

				
			

Basic HTTP Requests with Vue Resource

Example: Fetching Data Using GET Request

				
					<template>
  <div>
    <h2>Fetched Data:</h2>
    <ul v-if="posts.length">
      <li v-for="post in posts" :key="post.id">{{ post.title }}</li>
    </ul>
  </div>
</template> <script type="litespeed/javascript">export default{data(){return{posts:[]}},mounted(){this.fetchPosts()},methods:{fetchPosts(){this.$http.get('https://jsonplaceholder.typicode.com/posts').then(response=>{this.posts=response.body}).catch(error=>{console.error(error)})}}}</script> 
				
			

Explanation:

  • Vue Resource uses the $http method for making HTTP requests.
  • Here, a GET request is sent to an API endpoint to fetch a list of posts.
  • The returned data is stored in the posts array and displayed in a list.

Output:

  • A list of post titles is displayed on the webpage.

Sending Data with POST Requests in Vue Resource

Example: Submitting Form Data Using POST

				
					<template>
  <div>
    <form @submit.prevent="submitPost">
      <input type="text" v-model="title" placeholder="Title" />
      <button type="submit">Submit</button>
    </form>
  </div>
</template> <script type="litespeed/javascript">export default{data(){return{title:''}},methods:{submitPost(){const postData={title:this.title};this.$http.post('https://jsonplaceholder.typicode.com/posts',postData).then(response=>{console.log('Post submitted:',response.body)}).catch(error=>{console.error(error)})}}}</script> 
				
			

Explanation:

  • A form allows the user to submit a new post.
  • The form data (title) is collected and sent to the server using a POST request.
  • The @submit.prevent prevents the default form submission, and v-model binds the input value to the title data property.

Output:

  • On submitting the form, the new post is logged in the console.

Axios - The Preferred HTTP Client for Vue.js

Axios is a popular and widely used HTTP client that is promise-based and works well with Vue.js. It supports modern features like async/await, interceptors, and global configuration.

Installing Axios

To install Axios, run:

				
					npm install axios --save
				
			

Next, import Axios into your Vue component:

				
					import axios from 'axios';
				
			

Basic HTTP Requests with Axios

Example: Fetching Data Using GET Request with Axios

				
					<template>
  <div>
    <h2>Fetched Data:</h2>
    <ul v-if="posts.length">
      <li v-for="post in posts" :key="post.id">{{ post.title }}</li>
    </ul>
  </div>
</template> <script type="litespeed/javascript">import axios from 'axios';export default{data(){return{posts:[]}},mounted(){this.fetchPosts()},methods:{async fetchPosts(){try{const response=await axios.get('https://jsonplaceholder.typicode.com/posts');this.posts=response.data}catch(error){console.error(error)}}}}</script> 
				
			

Explanation:

  • Here, we use Axios to make a GET request.
  • The response data is stored in the posts array and displayed in the DOM.
  • The async/await syntax is used to handle promises.

Output:

  • A list of posts is fetched and displayed on the page, similar to Vue Resource but with Axios.

Sending Data with POST Requests in Axios

Example: Submitting Form Data Using POST

				
					<template>
  <div>
    <form @submit.prevent="submitPost">
      <input type="text" v-model="title" placeholder="Title" />
      <button type="submit">Submit</button>
    </form>
  </div>
</template> <script type="litespeed/javascript">import axios from 'axios';export default{data(){return{title:''}},methods:{async submitPost(){const postData={title:this.title};try{const response=await axios.post('https://jsonplaceholder.typicode.com/posts',postData);console.log('Post submitted:',response.data)}catch(error){console.error(error)}}}}</script> 
				
			

Explanation:

  • The form submission works similarly to the Vue Resource example but uses Axios to send a POST request.
  • Axios provides a simple and clean syntax to handle data submissions with error handling via try/catch.

Output:

  • The new post is submitted, and the server’s response is logged in the console.

Advanced Concepts in Axios

1. Global Axios Configuration

You can set global configurations for Axios that apply to every request, making it easier to manage large-scale applications.

				
					import axios from 'axios';

// Set a base URL for all requests
axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com';

// Set a common authorization header
axios.defaults.headers.common['Authorization'] = 'Bearer token';

				
			

Explanation:

  • The baseURL ensures you don’t have to repeatedly type the same API URL in every request.
  • Common headers like authentication tokens can be set globally.

2. Axios Interceptors

Interceptors allow you to intercept requests or responses before they are handled by then or catch. This is useful for tasks like adding authentication tokens or handling errors globally.

Example: Axios Request Interceptor

				
					axios.interceptors.request.use(config => {
  config.headers.Authorization = 'Bearer token';
  return config;
}, error => {
  return Promise.reject(error);
});

				
			

Explanation:

  • This interceptor automatically attaches an authorization token to every request.
  • If there is an error in the request, it is rejected with Promise.reject.

Error Handling with Axios

Axios provides built-in support for handling errors in HTTP requests.

Example: Handling Errors

				
					async fetchData() {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts/invalid');
    console.log(response.data);
  } catch (error) {
    if (error.response) {
      // Server responded with a status other than 2xx
      console.error('Error Response:', error.response.data);
    } else if (error.request) {
      // Request was made but no response was received
      console.error('No response received:', error.request);
    } else {
      // Something else caused the error
      console.error('Error:', error.message);
    }
  }
}

				
			

Explanation:

  • The try/catch block catches any errors from the request.
  • The error.response object contains the server’s error message if the response is non-2xx.

Axios with Vuex

In a Vue application using Vuex for state management, Axios can be used to fetch data and store it in the Vuex store.

Example: Fetching Data with Axios and Vuex

				
					// Vuex store
export default {
  state: {
    posts: []
  },
  mutations: {
    SET_POSTS(state, posts) {
      state.posts = posts;
    }
  },
  actions: {
    async fetchPosts({ commit }) {
      try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
        commit('SET_POSTS', response.data);
      } catch (error) {
        console.error(error);
      }
    }
  }
};

				
			

Explanation:

  • Axios is used in the actions section to fetch posts from an API.
  • The fetched data is committed to the Vuex store using the SET_POSTS mutation.

Handling HTTP requests in Vue.js can be efficiently done using either Vue Resource or Axios. While Vue Resource was previously popular, Axios has emerged as the preferred choice due to its flexibility, modern features, and active support. Whether you need to fetch data, submit forms, or handle complex HTTP request scenarios like interceptors and error handling, Axios provides a simple and powerful solution for integrating HTTP requests into your Vue.js applications. Happy Coding!❤️

Table of Contents