Axios secondary encapsulation example Demo in the project

Axios secondary encapsulation example Demo in the project

1. Why do packaging?

Facilitates overall code calling, public processing of requests, and personalized customization

2. Others have already encapsulated a lot, why not just modify and use it?

  • The packaging idea is not suitable for your own project
  • Inconvenient to call after encapsulation

3. Personal packaging demo

Code structure [based on vue]

Basic idea

Store all request interface addresses by module according to files, such as request/module/user user information related module [service]

2. Encapsulation methods and classes. Bind common request methods to all requests and process path parameters on the request URL

generateServer.js

import server from "../util/axiosConfig";
// Modify the basic configuration of axios and request configuration function request({
  url,
  method = "get",
  queryParm = {},
  body = {},
  pathParm = null,
  config = {},
}) {
  const configAxios = {
    method,
    ...config,
    url: dealRequestUrl(url, pathParm),
  };
  switch (method) {
    case "get":
      configAxios.params = queryParm;
      break;

    default:
      // Request methods 'PUT', 'POST', and 'PATCH'
      configAxios.data = body;
      break;
  }
  console.log('configAxios', configAxios)
  return server(configAxios);
}

function dealRequestUrl(url, pathParm) {
  if (!pathParm) return url;
  let dealurl = url;
  Object.keys(pathParm).forEach((ele) => {
    dealurl = dealurl.replace(`{${ele}}`, pathParm[ele]);
  });
  return dealurl;
}
class GenerateServer {
  constructor(url) {
    this.url = url;
  }
  getdata(parm) {
    console.log('parm', parm)
    return request({ ...parm, method: "get", url: this.url });
  }
  postdata(parm) {
    return request({ ...parm, method: "post", url: this.url });
  }
  deletedata(parm) {
    return request({ ...parm, method: "delete", url: this.url });
  }
}
export default GenerateServer;

3. Expose the whole

use

    import { userInfoServer } from "./request";
    .
    .
    .

    // Send request userInfoServer.getUserName
      .getdata({
        queryParm: {
          id: 223,
        },
      })
      .then((res) => {
        console.log("res", res);
      });
    // Send request userInfoServer.getUserName
      .postdata({
        body: {
          id: 223,
        },
      })
      .then((res) => {
        console.log("res", res);
      });
    // Send a get request with the request path containing the parameter userInfoServer.getUserList
      .getdata({
        queryParm: {
          id: 223,
        },
        pathParm: {
          id: 567,
        },
      })
      .then((res) => {
        console.log("res", res);
      });

Summarize:

The above encapsulation is mainly to split the request in a more detailed way to facilitate maintenance. It is also more convenient during development. For new interface requirements, you only need to add URl configuration and response generator configuration in the corresponding module. Then you can process the request in the business code. The path parameters and request body parameters are encapsulated, so you don't need to worry about the corresponding configuration when using them.

The above code does not handle file uploads, get request parameter strings, etc. But just add configuration in the corresponding axios. Easy to maintain.

This is the end of this article about Axios secondary packaging in the project. For more relevant Axios secondary packaging 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!

Code git: git

You may also be interested in:
  • An example of secondary encapsulation of axios in vue
  • Detailed explanation of using Vue secondary encapsulation axios as a plug-in
  • Example code of vue axios secondary packaging
  • Detailed explanation of Vue Axios secondary encapsulation
  • Implementation of secondary encapsulation of vue axios based on common business scenarios

<<:  Detailed explanation of how to install PHP7 on Linux

>>:  In-depth explanation of the maximum value of int in MySQL

Recommend

Detailed usage of Vue more filter widget

This article example shares the implementation me...

Analysis and description of network configuration files under Ubuntu system

I encountered a strange network problem today. I ...

How to convert a column of comma-separated values ​​into columns in MySQL

Preface Sometimes you come across business tables...

Summary of 4 methods of div+css layout to achieve 2-end alignment of css

The div+css layout to achieve 2-end alignment is ...

HTML framework_Powernode Java Academy

1. Framework A browser document window can only d...

How to solve the problem of character set when logging in to Linux

Character set error always exists locale: Cannot ...

Nginx one domain name to access multiple projects method example

Background Recently, I encountered such a problem...

Several ways to set the expiration time of localStorage

Table of contents Problem Description 1. Basic so...

CentOS7 64-bit installation mysql graphic tutorial

Prerequisites for installing MySQL: Install CentO...

What is WML?

WML (Wireless Markup Language). It is a markup la...

Solution to invalid margin-top of elements in div tags

Just as the title says. The question is very stran...

Detailed explanation of data types in JavaScript basics

Table of contents 1. Data Type 1.1 Why do we need...

A brief discussion on the magical slash in nginx reverse proxy

When configuring nginx reverse proxy, the slashes...

Brief analysis of the various versions of mysql.data.dll driver

Here is the mysql driver mysql.data.dll Notice: T...