Packaging and NPM package publishing for Axios

1. ajax status

      Ajax is the core technology behind most web applications, it allows pages to make asynchronous requests to web services, so data can be displayed without a page round-trip to the server with no refresh The term Ajax is not a technology, instead it
refers The method of script loading server data.
All modern browsers natively support XHR objects through the XMLHttpRequest constructor.
There are currently two Ajax APIs: early XMLHttpRequest and modern Fetch. At present, most Ajax libraries for XMLHttpRequest packaging are still used on the web side, such as: axios, jquery, SuperAgent, Request, etc.
Based on our business scenarios in actual projects, this article implements http requests for the encapsulation of axios, and releases them to the intranet NPM server. At present, the Vue3 technology projects we have involved have been put into use one after another, and We are also continuing to optimize.

2. Introduction to axios

      axios is a promise-based network request library for node.js and browsers. It is isomorphic (ie the same code can run in the browser and node.js). On the server side it uses the native node.js http module, and on the client side (browser side) it uses XMLHttpRequests.
Features:
· Create XMLHttpRequests from the browser · Create http requests
from node.js · Support Promise API · Intercept request and response · Transform request and response data · Cancel request · Automatically convert JSON data · Client support defense against XSRF





      axios is a lightweight HTTP client, it executes HTTP requests based on XMLHttpRequest service, supports rich configuration, supports Promise, and supports browser and Node.js terminals. Since Vue2.0, You Yuxi, the author of Vue, announced that he will cancel the official recommendation of vue-resource and recommend axios instead. Now axios has become the first choice of most Vue developers.

3. Encapsulate http

3-1. Abstract axios, create Class GAxios

3-1-1. Define parameter type

For the common configuration given by the official, combined with some common configurations we have in the project

// http请求配置
export interface RequestOptions {
    
    
  // 请求参数拼接到url
  joinParamsToUrl?: boolean;
  // 格式化请求参数时间
  formatDate?: boolean;
  //  是否处理请求结果
  isTransformRequestResult?: boolean;
  // 是否加入url
  joinPrefix?: boolean;
  // 接口地址, 不填则使用默认apiUrl
  apiUrl?: string;
  // 错误消息提示类型
  errorMessageMode?: 'none' | 'modal';
  // 自定义处理请求结果
  customTransformResult?: Function | null;
}

// Axios初始化配置,  AxiosRequestConfig对象为Axios的请求配置
export interface CreateAxiosOptions extends AxiosRequestConfig {
    
    
  prefixUrl?: string;
  transform?: AxiosTransform;
  requestOptions?: RequestOptions;
  messageError?: Function | null;
  modalError?: Function | null;
}

3-1-2. Create GAxios

Based on the above configuration information, we first create the axios class GAxios (the name is defined by yourself, mainly used to distinguish Axios objects)

export class GAxios {
    
    
  // TODO ......
}

The GAxios object should contain a series of operations for our Axios object: sample initialization, configuration items, interceptors, request methods, and so on.

export class GAxios {
    
    
  private axiosInstance: AxiosInstance;
  private options: CreateAxiosOptions;

  constructor(options: CreateAxiosOptions) {
    
    
    this.options = options;
    this.axiosInstance = axios.create(options);
  }
  
  // 创建axios实例
  private createAxios(config: CreateAxiosOptions): void {
    
    
    this.axiosInstance = axios.create(config);
  }
  
  // 拦截器配置
  private setupInterceptors(): void {
    
    
    // TODO ......
  }
  
  // 请求方法
  request<T>(config: AxiosRequestConfig, options?: RequestOptions): Promise<T> {
    
    
    // TODO ......
    
    return new Promise((resolve, reject) => {
    
    };
  }
}

3-1-3. Interceptor configuration

Interceptor defines four types: request/response interception, request/response error interception

// 请求之前的拦截器
requestInterceptors?: (config: AxiosRequestConfig) => AxiosRequestConfig;

// 请求之后的拦截器
responseInterceptors?: (res: AxiosResponse<any>) => AxiosResponse<any>;

// 请求之前的拦截器错误处理
requestInterceptorsCatch?: (error: Error, options?: CreateAxiosOptions) => void;

// 请求之后的拦截器错误处理
responseInterceptorsCatch?: (error: Error, options?: CreateAxiosOptions) => void;

3-1-4. Define the request method

class GAxios {
    
    
    // 请求方法
    request<T>(config: AxiosRequestConfig, options?: RequestOptions): Promise<T> {
    
    
        // Merge参数opt
        
        // 自定义请求转换

        // 取消重复请求
      
        // 拦截器

        // 请求方法
        return new Promise((resolve, reject) => {
    
    
            this.axiosInstance
                .request(opt)
                .then((res) => {
    
    
                    
                    resolve(res);
                })
                .catch((e: Error) => {
    
    
                    
                    reject(e);
                });
        });
    }
}

3-2. Create Class AxiosHttp

// GAxios的具体实现
class AxiosHttp {
    
    
    private http: GAxios = null;
}

3-2-1. Define default parameters

      {
    
    
            timeout: 6 * 10 * 1000,// 1min
            // 基础接口地址
            baseURL: '',
            // 接口可能会有通用的地址部分,可以统一抽取出来
            prefixUrl: '',
            headers: {
    
     'Content-Type': ContentTypeEnum.JSON },
            // 数据处理方式
            transform,
            // 配置项,下面的选项都可以在独立的接口请求中覆盖
            requestOptions: {
    
    
                // 默认将prefix 添加到url
                joinPrefix: true,
                // 需要对返回数据进行处理
                isTransformRequestResult: true,
                // post请求的时候添加参数到url
                joinParamsToUrl: false,
                // 格式化提交参数时间
                formatDate: true,
                // 消息提示类型
                errorMessageMode: 'none',
                // 接口地址
                apiUrl: '',
                // 自定义数据转换
                customTransformResult: data => data,
                // 自定义消息框方法
                messageBox: data => data
            }
        }

3-2-2. Create http object

Instantiate the GAxios object inside the AxiosHttp class

this.http = new GAxios({
    
    ...});

3-2-3. Implement common request methods

Inside the AxiosHttp class, we provide several commonly used request methods: get, post, put, delete
In addition, we still need to improve the http.request method to meet the needs of more scenarios.

3-2-4. Setting token method

The token information is usually carried in the request header, so we need to provide a custom setting Heder method

public setToken(token: string): void {
    
    
  this.http.setHeader({
    
    
      Authorization: `Bearer ${
      
      token}`
  });
}

3-2-5. Return the built-in defHttp object

public getInstance(): GAxios {
    
    

        return this.http;
}

By obtaining the objects of built-in Axios, more different scenarios can be realized

3. Export in the vue3 environment

In vue3, components are registered through the app.use method. Here we realize the registration and use of the current http library. When we call the app.use method, the actual implementation is the install method of the current component

3-3-1. Install method

const uniqueKey = Symbol();
const install = (app: App, config: Partial<CreateAxiosOptions>): void => {
    
    

    app.provide(uniqueKey, new AxiosHttp(config));
}


export default {
    
    
    install
}

3-3-2. Using provide and inject

export default defineComponent({
    
    
  setup() {
    
    
      const axiosHttp = useAxiosHttp();
      // axiosHttp 即为注入的http对象
      
      // 在实际开发场景中,axiosHttp可以在项目入口处挂载到全局对象
      // 例:app.config.globalProperties.$http = axiosHttp;
  }
});

3-3-3. Publish the current package

After testing the use cases in the Demo, we are ready to release our first version of the package. Here we take the private npm server as an example.

  1. Change the current source to the intranet server through nrm.
  2. Login account npm login
  3. publish npm publish

4. Introduction to common component development specifications

Usually, the development process of a set of components, libraries, etc. is relatively cumbersome, and different teams will make choices according to the time situation.
No matter how to simplify branch management, naming conventions, communication rules, etc., these are unavoidable.

Front-end industry-2.Component R&D process.png

5. Practice

In our business project (vue3), install our published package. Specify the
source address of the package starting with @gfe through the .npmrc file
npm install @gfe/request --save
yarn add @gfe/request

6. Access and use

import {
    
     useLogout } from "@/hooks/useLogout";
import router from "@/router";
import {
    
     BASE_API } from '@/utils/env';
import AxiosHttp from '@gfe/request';
import {
    
     message, Modal } from 'ant-design-vue';
import {
    
     App } from 'vue';

export function setupHttp(app: App<Element>) {
    
    

    app.use(AxiosHttp, {
    
    
        baseURL: BASE_API,
        messageError: async (msg: string, status: number) => {
    
    
            if (`${
      
      status}` == `401`) {
    
    
                await useLogout();
                router.replace({
    
     name: 'Login' });
            }
            message.error(msg);
        },
        modalError: (msg: string) => {
    
    
            Modal.error({
    
    
                title: '错误提示',
                content: msg
            })
        }
    });
}

7. Summary

  1. The current component library document is displayed using vuepress, and the source code is in the /docs folder
  2. Configure warehouse authentication information.npmrc, which is used to read or upload npm packages in private warehouses, without performing npm login operation every time you publish
always-auth=true
_auth="用户名:密码"的base64编码
  1. Source address
    https://github.com/gfe-team/gfe-request

Guess you like

Origin blog.csdn.net/gaojinbo0531/article/details/129294400
Recommended