Secondary packaging of axios (concise)

Secondary packaging of axios

preface

Why do you need secondary packaging

api unified management, no matter how many interfaces, all interfaces can be very clear and easy to maintain

1, Creation of basic page

First, you need to prepare a vue project

  1. First open the folder where the project needs to be created. Enter cmd below to open the window
  2. Enter the name of the vue create project in the window
  3. Choose to use vue2 X version
  4. Wait for the creation. After that, enter the folder and enter npm run serve on the console

2, Use steps

1. Introduce related packages

First, we need to download the relevant packages:

We need to download axios and element UI

npm i axios@0.18.1
npm i element-ui@2.13.2

2. Preparation of documents

Create the folder utils under src, and create the file request js

Write the following code (example):

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

const service = axios.create({
  baseURL: '/dev-api', 
  timeout: 5000 
})

// request interceptor 
service.interceptors.request.use(
  config => {

    return config
  },
  error => {
    // do something with request error
    console.log(error) 
    return Promise.reject(error)
  }
)

// Response interceptor
service.interceptors.response.use(

  response => {
    return response.data
  },
  error => {
    console.log('err' + error)
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

Create a new index under api JS file is used to summarize the interface codes of various parts, which are listed below:

// Expose modules uniformly
import * as attr from './product/attr'

//External exposure
export default {
     attr
}

In main JS entry file can be imported and mounted on the Vue prototype for easy calling. The code is as follows:

import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

// Introducing api request interface
import API from '@/api'

Vue.prototype.$API = API

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

At this point, our simple packaging is ready

3. Preparation of requests

Create a folder api under src to store the interfaces of various parts, and then create a file product under the api folder to collect products

Part of the interface, and create attr JS file, which is used to write the request. The sample code is as follows:

// Data of product management module
import request from '@/utils/request'

// Get classification list
export function reqCateGoryList() {
  return request({
    url: `/admin/product/getCategory1`,
    method: 'get'
  })
}

4. Solve cross domain problems

In the development of the front-end, in order to avoid the cross domain problem of some data initiation and request addresses, we need to configure agents to solve it

Cross domain

We need to find Vue config. JS file, write code to solve cross domain problems. The code of the file is as follows

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true
})

module.exports = {
  devServer: {
    open: true,
    // Solve the problem of agent cross domain
    proxy: {
      '/dev-api': {
        target: 'http://39.98.123.211',
        pathRewrite: { '^/dev-api': '' } // The dev API here must be the same as the previous baseURL
      }
    }
  }
}

5. Test use

Simply write app Vue's code is used for testing

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <button @click="reqCateGory1List">test</button>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      list1: ''
    }
  },
  methods: {
    async reqCateGory1List() {
      const res = await this.$API.attr.reqCateGoryList()
      if (res.code == 200) {
        this.list1 = res.data
        console.log(res.data)
      }
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

At this point, the console can output data

summary

The secondary encapsulation of axios shows the idea of modularization of code, and the interface division of each region is very clear

Later, combined with vuex, we can get good management

Tags: Javascript Vue.js

Posted by dannylewin on Sat, 16 Apr 2022 06:36:30 +0930