Home Web Front-end JS Tutorial Use axios to encapsulate the fetch method and call

Use axios to encapsulate the fetch method and call

Jun 07, 2018 pm 04:28 PM
axios fetch encapsulation

Below I will share with you an example of encapsulating the fetch method and calling it based on axios. It has a good reference value and I hope it will be helpful to everyone.

For basic axios usage, please see the axios official website

//依赖于axios对私有ajax进行修改
import Qs from 'qs'
import axios from 'axios'
import router from 'router/index'
import {errorPrompt, loading, closeLoading} from 'util/util'
export const status = {
 SUCCESS: '100',
 NET_ERR: '101', // 网络连接异常,请稍候再试
 BIZ_ERR: '103', // 业务请求异常
 NO_AUTH: '104'
}
export function fetch(options) {
 return new Promise((resolve, reject) => {
 let instance = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 2000,
  headers: {
  // "tracecode": window.encodeURIComponent(JSON.stringify({"ua":"","cv":"20161230","token":"3dwo0onUUsPKVJcP8tk","os":"windows10","app":"kind","ws":"1*1","pkey":"f8caf7d7-a5d4-4710-b06f-28a922b6a467"}))
  "tracecode": commonBizHeader(isManager(options)),
  'Content-Type': 'application/x-www-form-urlencoded'
  },
  transformRequest: [function (data) {
  // Do whatever you want to transform the data
  let ret = ''
  for (let it in data) {
   ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
  }
  return ret
  }]
 });
 instance.interceptors.request.use(function (response) {
  // 请求拦截
  loading();
  return response;
 }, function (error) {
  console.log('error 请求拦截 : ', error)
  return Promise.reject(error);
 });
 instance(options)
  .then(response => {
   const res = response.data;
   if (res.errorCode != status.SUCCESS) {
   switch (res.errorCode) {
    case status.NET_ERR: {
    errorPrompt(res.errorMsg)
    reject(res)
    break;
    }
    case status.BIZ_ERR: {
    errorPrompt(res.errorMsg)
    reject(res)
    break;
    }
    case status.NO_AUTH: {
    errorPrompt(res.errorMsg)
    let session = require("storejs")
    if (isManager(options)) { // 管理端
     session.remove("managerUserToken")
     router.push({path: '/manager/login'})
    } else {
     session.remove("clientUserToken")
     router.push({path: '/client/login'})
    }
    reject(res)
    break
    }
   }
   }
   closeLoading();
   resolve(res);
  }).catch(error => {
   closeLoading();
   errorPrompt('网络连接错误,请检查您的网络')
   console.log('error', error); // for debug
   reject(error);
  });
 });
}
function commonBizHeader (isManager) {
 let session = require("storejs");
 let params = {}
 params['ua'] = window.navigator.userAgent.toLowerCase()
 params['cv'] = '123456'
 params['ws'] = window.screen.height + '*' + window.screen.width
 params['token'] = "123456"
 params['os'] = window.navigator.appCodeName
 if (isManager) {
 params['token'] = session.get('managerUserToken') // 管理 - 用户令牌
 } else {
 params['token'] = session.get('clientUserToken') // 用户 - 用户令牌
 }
 params['app'] = 'kind'
 let UUID = session.get('pkey')
 if (!UUID) {
 UUID = getUUID()
 window.localStorage.setItem('pkey', UUID)
 }
 return encodeURIComponent(JSON.stringify(params))
}
function isManager(options) {
 return options && options.url && options.url.indexOf("/api/worker") != -1
}
/**
 * 获取UUID
 * @returns {string}
 */
export function getUUID() {
 let len = 32 // 32长度
 let radix = 16 // 16进制
 let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
 let uuid = []
 let i
 radix = radix || chars.length
 if (len) {
 for (i = 0; i < len; i++) {
  uuid[i] = chars[0 | Math.random() * radix]
 }
 } else {
 var r
 uuid[8] = uuid[13] = uuid[18] = uuid[23] = &#39;-&#39;
 uuid[14] = &#39;4&#39;
 for (i = 0; i < 36; i++) {
  if (!uuid[i]) {
  r = 0 | Math.random() * 16
  uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]
  }
 }
 }
 return uuid.join(&#39;&#39;).toLowerCase()
}
Copy after login

This is in the vue project: the calling method in the api is as follows (react has just started I am still doing a simple demo)

import {fetch} from &#39;api/fetch&#39;
export const callAuthCode = (userPhone) => {
 return fetch({
 url: &#39;/api/auth/code&#39;,
 method: &#39;post&#39;,
 data: ({
  userPhone: userPhone,
 }),
 })
}
Copy after login

Because our backend requires strict distinction between get/post requests, so the encapsulated method call must contain method. If the backend has been processed, all can be posted. request, you can refer to the axios official website and change all methods to .post

Description of the fetch method: It mainly encapsulates request interception and response interception. The default request body is converted from json format to form format. Of course, these They can all be found on the axios official website, but they are just collected. Please do not apply the request header part directly. This is a special configuration required by our backend. The three ends of the backend interface are shared and must be distinguished. Where is the call

I compiled the above for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Concept and usage of command mode in JS (detailed tutorial)

How to implement callbacks using Promise in WeChat applet ?

The problem of failure to install Electron using npm

The above is the detailed content of Use axios to encapsulate the fetch method and call. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Choice of data request in Vue: Axios or Fetch? Choice of data request in Vue: Axios or Fetch? Jul 17, 2023 pm 06:30 PM

Choice of data request in Vue: AxiosorFetch? In Vue development, handling data requests is a very common task. Choosing which tool to use for data requests is a question that needs to be considered. In Vue, the two most common tools are Axios and Fetch. This article will compare the pros and cons of both tools and give some sample code to help you make your choice. Axios is a Promise-based HTTP client that works in browsers and Node.

Efficiently utilize Vue and Axios to implement batch processing of front-end data Efficiently utilize Vue and Axios to implement batch processing of front-end data Jul 17, 2023 pm 10:43 PM

Efficiently utilize Vue and Axios to implement batch processing of front-end data. In front-end development, data processing is a common task. When we need to process a large amount of data, processing the data will become very cumbersome and inefficient if there is no effective method. Vue is an excellent front-end framework, and Axios is a popular network request library. They can work together to implement batch processing of front-end data. This article will introduce in detail how to efficiently use Vue and Axios for batch processing of data, and provide relevant code examples.

TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year Apr 17, 2024 pm 08:00 PM

According to news from this site on April 17, TrendForce recently released a report, believing that demand for Nvidia's new Blackwell platform products is bullish, and is expected to drive TSMC's total CoWoS packaging production capacity to increase by more than 150% in 2024. NVIDIA Blackwell's new platform products include B-series GPUs and GB200 accelerator cards integrating NVIDIA's own GraceArm CPU. TrendForce confirms that the supply chain is currently very optimistic about GB200. It is estimated that shipments in 2025 are expected to exceed one million units, accounting for 40-50% of Nvidia's high-end GPUs. Nvidia plans to deliver products such as GB200 and B100 in the second half of the year, but upstream wafer packaging must further adopt more complex products.

Vue and Axios implement synchronous processing of asynchronous data requests Vue and Axios implement synchronous processing of asynchronous data requests Jul 17, 2023 am 10:13 AM

Vue and Axios implement synchronous processing of asynchronous data requests Introduction: In modern front-end development, because the page needs to obtain data through asynchronous data requests and dynamically display it, asynchronous processing has become an inevitable requirement. However, asynchronous data requests often cause code logic to become complex and difficult to maintain. In the Vue framework, the Axios library can be used to easily implement synchronous processing of asynchronous data requests, thereby improving the readability and maintainability of the code. 1. Introduction to Vue Vue is a lightweight front-end framework.

AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix Jul 18, 2024 am 02:04 AM

This website reported on July 9 that the AMD Zen5 architecture "Strix" series processors will have two packaging solutions. The smaller StrixPoint will use the FP8 package, while the StrixHalo will use the FP11 package. Source: videocardz source @Olrak29_ The latest revelation is that StrixHalo’s FP11 package size is 37.5mm*45mm (1687 square millimeters), which is the same as the LGA-1700 package size of Intel’s AlderLake and RaptorLake CPUs. AMD’s latest Phoenix APU uses an FP8 packaging solution with a size of 25*40mm, which means that StrixHalo’s F

How do C++ functions improve the efficiency of GUI development by encapsulating code? How do C++ functions improve the efficiency of GUI development by encapsulating code? Apr 25, 2024 pm 12:27 PM

By encapsulating code, C++ functions can improve GUI development efficiency: Code encapsulation: Functions group code into independent units, making the code easier to understand and maintain. Reusability: Functions create common functionality that can be reused across applications, reducing duplication and errors. Concise code: Encapsulated code makes the main logic concise and easy to read and debug.

Vue and Axios implement error handling and prompt mechanism for data requests Vue and Axios implement error handling and prompt mechanism for data requests Jul 17, 2023 am 09:04 AM

Vue and Axios implement error handling and prompt mechanism for data requests Introduction: In Vue development, Axios is often used for data requests. However, in the actual development process, we often encounter request errors or the server returns error codes. In order to improve the user experience and detect and handle request errors in a timely manner, we need to use some mechanisms for error handling and prompts. This article will introduce how to use Vue and Axios to implement error handling and prompt mechanisms for data requests, and provide code examples. Install Axi

Packaging technology and application in PHP Packaging technology and application in PHP Oct 12, 2023 pm 01:43 PM

Encapsulation technology and application encapsulation in PHP is an important concept in object-oriented programming. It refers to encapsulating data and operations on data together in order to provide a unified access interface to external programs. In PHP, encapsulation can be achieved through access control modifiers and class definitions. This article will introduce encapsulation technology in PHP and its application scenarios, and provide some specific code examples. 1. Encapsulated access control modifiers In PHP, encapsulation is mainly achieved through access control modifiers. PHP provides three access control modifiers,

See all articles