Use of Axios in Vue

Axios is an HTTP client based on Promise for browsers and NodeJS, which is essentially a wrapper around native XHR, but it’s an implementation version of Promise. It is common for us to use Axios in Vue projects.

Used alone

Let’s start with the basic usage of axios: Get a live segment, display it in a list, and loading it.

Start with a simple button and table (elementUI)

    <template>
      <div class="main">
        <el-button type="primary" size="default" @click="getJokes"
          ></el-button ><el-table v-loading="loading" :data="jokeList" border stripe>
          <el-table-column prop="sid" label="Section Number" width="180">
            <template slot-scope="scope">
              <el-tag type="primary" disable-transitions>{{
                scope.row.sid
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="Title" width="180"> </el-table-column>
          <el-table-column prop="text" label="Content"> </el-table-column>
        </el-table>
      </div>
    </template>
Copy the code

Then click the button to call the API to fetch the content. The basic use of Axios is:

     axios.get(APIURL).then(response= >()}Copy the code

We place an Axios asynchronous request in a created or Mounted hook. If we want to do something personalized before and after the request is sent and received, we can use the Axios interceptor

    /* Request interceptor */
    axios.interceptors.request.use((config) = > {return config  });
    /* Response interceptor */
    axios.interceptors.response.use((config) = > {return config  });
Copy the code

In this way, the loading logic can be implemented in the interceptor.

    <script>
    import axios from "axios";
    export default {
      name: "Test2"./** * Data definition */
      data() {
        return {
          jokeList: [].loading: false}; },/** ** feature function */
      methods: {
        getJokes() {
          axios
            .get("https://api.apiopen.top/getJoke? page=1&count=2&type=text")
            .then((res) = > {
              this.jokeList = res.data.result; }); }},created() {
        /* Request interceptor */
        axios.interceptors.request.use(
          (config) = > {
            // What to do before sending the request
            this.loading = true;
            console.log("config", config);
            return config;
          },
          (error) = > {
            console.log(error); // for debug
            return Promise.reject(error); });/* Response interceptor */
        axios.interceptors.response.use(
          (response) = > {
            this.loading = false;
            console.log("res", response);
            return response;
          },
          (er) = > {
            return Promise.reject(er); }); }}; </script>Copy the code

Take a look at the effect:

Well, it looks something like this, click and load, and display the data; Now the uninstallation of the request should be nipped in your component, but at work our asynchronous request is generally wrapped, not each component is written, the following look at the process of encapsulation;

Axios encapsulation processing

1. Write axios logic first

Define an axiosutils.js file somewhere in the project (the name of the file is arbitrary), implement axios encapsulation, and implement the interceptor:

import axios from 'axios'
import {
  Message
} from 'element-ui'

// Create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 5000 // Request timeout
})

// Request interceptor
service.interceptors.request.use(
  config= > {
    console.log('config', config)
    // What to do before sending the request
    return config
  },
  error= > {
    console.log(error)
    return Promise.reject(error)
  }
)

// Response interceptor
service.interceptors.response.use(
  response= > {
    console.log(response)
    const res = response.data
    // 200 is a self-defined status code
    if(res.statusCode ! = =200) {
      Message({
        message: res.message || 'Error'.type: 'error'.duration: 5 * 1000
      })

      /* Some other logic can be written here */
      return Promise.reject(new Error(res.message || 'Error'))}else {
      return res
    }
  },
  error= > {
    console.log('err' + error)
    Message({
      message: error.message,
      type: 'error'.duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
export default service
Copy the code

2. Use wrapped AXIOS where the interface is defined

    import axiosRequest from '.. /utils/axiosRequest';  // Import the wrapped AXIos instance
    /** * get the real time segment *@param {*} The data parameter *@returns * /
    export function getJokes(data) {
      return axiosRequest({
        url: 'https://api.apiopen.top/getJoke? page=1&count=2&type=text'.method: 'post'.// Request mode post\get\put\delete......
        data / / parameters})}/* Other interface information */

    export function getInfo(token) {
      return axiosRequest({
        url: ' '.method: 'get'.params: {
          token
        }
      })
    }

    export function logout() {
      return axiosRequest({
        url: ' '.method: 'post'})}Copy the code

3. The final step is to use the created API inside the component

    <template>
      <div class="main">
        <el-button type="primary" size="default" @click="getJokes"
          ></el-button ><el-button type="primary" size="default" @click="getJokeList"
          ></el-button ><el-table v-loading="loading" :data="jokeList" border stripe>
          <el-table-column prop="sid" label="Section Number" width="180">
            <template slot-scope="scope">
              <el-tag type="primary" disable-transitions>{{
                scope.row.sid
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="Title" width="180"> </el-table-column>
          <el-table-column prop="text" label="Content"> </el-table-column>
        </el-table>
      </div>
    </template>

    <script>
    import axios from "axios";
    import { getJokes } from ".. /api/user";
    export default {
      name: "Test2"./** * Data definition */
      data() {
        return {
          jokeList: [].loading: false}; },/** ** feature function */
      methods: {
        getJokes() {
          // axios
          // .get("https://api.apiopen.top/getJoke? page=1&count=2&type=text")
          // .then((res) => {
          // this.jokeList = res.data.result;
          / /});
        },
        getJokeList() {
          this.loading = true;
          const params = {};
          getJokes(params).then((res) = > {
            if (res) {
              // TODO: 
              this.loading = false;
            }
            console.log("The results", res); }); }},// created() {
      // * Request interceptor */
      // axios.interceptors.request.use(
      // (config) => {
      // // What do you do before sending a request
      // this.loading = true;
      // console.log("config", config);
      // return config;
      / /},
      // (error) => {
      // console.log(error); // for debug
      // return Promise.reject(error);
      / /}
      / /);
      // * Response interceptor */
      // axios.interceptors.response.use(
      // (response) => {
      // this.loading = false;
      // console.log("res", response);
      // return response;
      / /},
      // (er) => {
      // return Promise.reject(er);
      / /}
      / /);
      // },
    };
    </script>

    <style>
    </style>
Copy the code

So that basically encapsulates it; In fact, there are some status code cases that can be handled during encapsulation.