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

Three ways to implement virtual hosts under Linux7

1. Same IP address, different port numbers Virtua...

Detailed explanation of the use of umask under Linux

I recently started learning Linux. After reading ...

Use Angular CDK to implement a Service pop-up Toast component function

Table of contents 1. Environmental Installation 2...

MySQL optimization: use join instead of subquery

Use JOIN instead of sub-queries MySQL supports SQ...

Docker nginx example method to deploy multiple projects

Prerequisites 1. Docker has been installed on the...

JavaScript immediate execution function usage analysis

We know that in general, a function must be calle...

Summary of methods to prevent users from submitting forms repeatedly

Duplicate form submission is the most common and ...

Node.js uses express-fileupload middleware to upload files

Table of contents Initialize the project Writing ...

A brief discussion on the solution of Tomcat garbled code and port occupation

Tomcat server is a free and open source Web appli...

How to introduce img images into Vue pages

When we learn HTML, the image tag <img> int...

How to modify the default encoding of mysql in Linux

During the development process, if garbled charac...

Tutorial on installing MySQL8 compressed package version on Win10

1 Download MySQL8 from the official website and i...

Some problems you may encounter when installing MySQL

Question 1: When entering net start mysql during ...