Axios API Response Status Code Best way To Handle In Vue

  • 25-07-2022
  • 1404
  • Vue
  • Haresh Chauhan

If You Not Getting API Request Response Code Using Axios? This article will help you Best way To Create Axios requests and handle API responses very well in vue js large projects.

The best way to create an Axios request and send an HTTP API request or in other words create a common HTTP request file for handling the whole project API request if you are not getting validateStatus code from the API response this post will help you to all that questions answer.

To handle API response status code using Axios is very much important to know API response results whether the API is got a successful response and any validation or serverside error.

Having ended this post you will learn how to create Axios API request and send a common HTTP file for the whole project to handle status code and want to send token.

Also, you can easy to handled authorize token API using the header and API timeout set or in extra you can handle validation response and status from the browser.

In this post, I have created an http folder inside the src folder and in the http folder, I have created a js named http-common.js. In this file, I have imported Axios and created requests, and exported them as HTTP const variable.

Step 1: Install Axios In Project

I have already written an article on installing Axios in the vue project, just click on the below link and install Axios in your project.

[Install] Vue Axios Npm Library Guideline And Basic Usage In Vue Project

Step 2: Create HTTP File

In this step, we will create an HTTP common js file in the src/http path. In the http folder, you have to create yourself, and then inside this folder create the http-common.js file.

After creating the file and folder we will import "Axios" in this file. and will create an Axios request from the imported Axios.

To create an object I will pass some attributes for use all common Axios send API requests and API responses. First, I have passed baseURL in this attribute I will pass my API base URL which will stay common for all API requests.

In the second responseType attribute in this, I will define the response type expected to form the API. In the third timeout, you can set this attribute if you want to wait for a response just for some specific time else will fail. the fourth attribute is params for passing the parameter inside the URL.

The last attribute for handling the status code of API requests and responses from the server side. Based on the status code you can easy to justify API success response and validation error and unauthorized status code from the server side.

src/http/http-common.js
import axios from 'axios'

export const HTTP = axios.create({
    baseURL: `http://jsonplaceholder.typicode.com/`,
    responseType: 'json',
    timeout: 60000,
    params: {},
    validateStatus: function(status) {
        if (status == 401) {
            // 401 unauthorized

            // DO YOUR UNAUTHORIZED CODE HERE
        } else {

            return status >= 200 && status < 501 // default
        }
    },
})

Step 3: Usage Common Axios Request

I have made a PostComponent just for checking common Axios which I made in the early step. import HTTP common component from the http folder as you can see in the below example.

And inside the created method you can see, I just need to define the method and inside the method just passed the endpoint of the URL and handled the API response.

src/components/PostComponent.vue
<template>
  <div>
      <ul v-for="(post,index) in posts" :key="index">
          <li>{{post}}</li>
      </ul>
  </div>
</template>
    
<script>

import { HTTP } from '../http/http-common';
  
export default {
  name:'PostComponent',

  data() {
    return {
      posts: [],
        errors: []
    }
  },

  created() {
    HTTP.get(`posts`).then(response => {
      this.posts = response.data
    })
    .catch(e => {
      this.errors.push(e)
    })
  }
}
</script>

So this is the common API request handled Axios request using you can easy to handle whole project request very easily and without and long problem. Just import in component and use. If you don't want to import in each component just import in the main.js file which will work globally.


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :