How to encapsulate axios in Vue project (unified management of http requests)

How to encapsulate axios in Vue project (unified management of http requests)

1. Requirements

When using the Vue.js framework to develop front-end projects, ajax requests to the server interface are often sent. During the development process, axios needs to be further encapsulated to facilitate its use in the project.

2. Vue project structure

Create a Vue project locally with the following directory structure:

- public static resource files
-src
|- assets static resource directory
|- components public component directory
|- http axios package directory
|- router routing management directory
|- store state management directory
|- views view component directory
|- App.vue root component
|- main.js entry file
- package.json npm configuration file

Create an http directory in the Vue project as the management directory of axios. There are two files in the http directory, namely

  • /http/index.js file that encapsulates the axios method
  • /http/api.js Unified management interface file

3. Code Examples

The code of the /http/api.js file is as follows:

export default {
    'users_add': '/users/add',
    'users_find': '/users/find',
    'users_update': '/users/update',
    'users_delete': '/users/delete'
}

The code of the /http/index.js file is as follows:

import axios from 'axios'
import api from './api'

//Create an axios instance object let instance = axios.create({
    baseURL: 'http://localhost:3000', //server address timeout: 5000 //default timeout duration})

//Request interceptor instance.interceptors.request.use(config=>{
    //Write the code for request interception here, which is generally used to pop up the loading window console.log('Requesting...')
    return config
},err=>{
    console.error('Request failed',err)
})

//Response interceptor instance.interceptors.response.use(res=>{
    //Process the response data here console.log('Request successful!')
    return res //The returned object will be passed to the response object of the request method},err=>{
    // Response error handling console.log('Response failed!', err)
    // return Promise.reject(err);
})

//Encapsulate axios request method, parameter is configuration object //option = {method,url,params} method is request method, url is request interface, params is request parameter async function http(option = {}) {
    let result = null
    if(option.method === 'get' || option.method === 'delete'){
     //Handle get and delete requests await instance[option.method](
                api[option.url],
                {params: option.params}
          ).then(res=>{
            result = res.data
        }).catch(err=>{
            result = err
        })
    }else if(option.method === 'post' || option.method === 'put'){
     //Process post and put requests await instance[option.method](
                api[option.url],
                option.params
            ).then(res=>{
            result = res.data
        }).catch(err=>{
            result = err
        })
    }

    return result
}

export default http

Import the encapsulated /http/index.js file into the main.js entry file. The sample code is as follows:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import http from './http'

Vue.config.productionTip = false
Vue.prototype.$http = http

Vue.use(Elementui)

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

Test the axios request in the App.vue root component. The sample code is as follows:

<template>
  <div>
    <button @click="getDate">Send request</el-button>
  </div>
</template>

<script>
export default {
  methods: {
    getDate(){
      this.$http({
        method: 'get',
        url: 'users_find'
      }).then(res=>{
        console.log(res)
      })

    }
  }
}
</script>

There needs to be an http://localhost:3000/users/find interface here, otherwise the request will fail!

4. Effect Demonstration

Start the Vue project and access the address of the Vue project in the browser. My address is http://localhost:8080. Click the button to send the request. The result is shown in the figure below.

At this point, a simple axios encapsulation has been completed in the Vue project. You can also encapsulate axios according to your actual needs. This article is just for reference.

This is the end of this article about how to encapsulate axios (unified management of http requests) in Vue projects. For more relevant Vue encapsulation axios management http request content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to encapsulate axios request with vue
  • Vue application example code based on axios request encapsulation
  • Vue3+TypeScript encapsulates axios and implements request calls
  • Vue+axios encapsulates requests to separate the front and back ends
  • Steps for Vue to encapsulate Axios requests and interceptors
  • How to use Axios to encapsulate http requests in Vue projects
  • Vue axios repeated click cancel the last request encapsulation method
  • Encapsulation request of axios in vue project

<<:  Detailed explanation of InnoDB storage files in MySQL

>>:  Detailed explanation of EXT series file system formats in Linux

Recommend

Linux 6 steps to change the default remote port number of ssh

The default ssh remote port in Linux is 22. Somet...

Basic ideas for finding errors in Web front-end development

WEB development mainly consists of two interactio...

How to configure two-way certificate verification on nginx proxy server

Generate a certificate chain Use the script to ge...

Problems with Vue imitating Bibibili's homepage

Engineering Structure The project is divided into...

Query process and optimization method of (JOIN/ORDER BY) statement in MySQL

The EXPLAIN statement is introduced in MySQL quer...

Analysis of the reasons why MySQL field definitions should not use null

Why is NULL so often used? (1) Java's null Nu...

Make a nice flip login and registration interface based on html+css

Make a nice flip login and registration interface...

Implementation of Docker deployment of web projects

The previous article has installed the docker ser...

mysql 5.6.23 winx64.zip installation detailed tutorial

For detailed documentation on installing the comp...

Solve the abnormal error when building vue environment with webpack

Table of contents First, configure package.json T...

MySQL SHOW PROCESSLIST assists in the entire process of troubleshooting

1. SHOW PROCESSLIST command SHOW PROCESSLIST show...

Summary of a CSS code that makes the entire site gray

In order to express the deep condolences of peopl...

Linux nohup to run programs in the background and view them (nohup and &)

1. Background execution Generally, programs on Li...

Teach you how to use vscode to build a react-native development environment

question The code has no prompt: Many non-front-e...