Tag:vue axios封装
Article From:https://www.cnblogs.com/zhouyangla/p/9121779.html

Since Vue2.0 recommended that you use Axios, Axios is being understood by more and more people. Using Axios to initiate a request is a simple thing for everyone, but Axios does not carry out encapsulation reuse, the project is growing, and the code redundancy is caused. onOne thing that would be very troublesome. So this article will give you a detailed description of how to encapsulate requests and reuse requests in project components. A friend in need can make a reference.

basic requirements for encapsulation

  • Unified URL configuration
  • Unified API request
  • request (Request interceptor, for example, bring token and set up the request head.
  • response (Response) interceptors, such as unified error handling, page redirection, etc.
  • If necessary, combine Vuex with global loading animation or error handling.
  • Encapsulate Axios as a Vue plug-in

file structure

Build a new HTTP folder under the SRC directory

config.js axiosDefault configuration
api.js Two package Axios, interceptor, etc.
interface.js Request interface file
index.js Encapsulate Axios into a plug-in


Please refer to the official document of Axios for complete configuration

export default {
  method: 'get',
  // Basic URL prefixBaseURL:'https://www.example.com/api',/ / request header informationHeaders: {'Content-Type':'appliCation/json; charset=UTF-8'},/ / parametersData: {},/ / set timeout timeTimeout: 10000,/ / carry voucherWithCrEdentials: true,/ / return data typeResponseType:'json'}


import axios from 'axios';
import config from './config';
import qs from 'qs';
import Cookies from "js-cookie";
import router from '@/router'

// Using vuex as a global loading/ / import store from'@/store'Export default function $axios (options) {RetuRN new Promise ((resolve, reject) => {Const instance = axios.create ({BaseURL: config.bAseURL,Headers: {},TransformResponse: [function (data) {]]]})/ / requeSt interceptorInstance.interceptors.request.use (Config => {Let token = Cookies.get ('MarkToken')/ / 1. when the request starts, you can open full screen loading animation with vuex./ / console.log (store.state.loadinG)/ / console.log ('ready to send request...')/ / 2. with tokenIf (token) {Config.hEaders.accessToken = token} else {/ / redirects to the login pageRouter.push ('/login')}/ / 3., according to the request method, serialize the parameters to be serialized according to the back-end requirement.If (config.method = = ='post') {If (config.data.__proto__ = = = FormData.prototype)Config.url.endsWith ('path')Config.url.endsWith ('mark')Config.url.endsWith ('patchs')) {} else {Config.data = qs.stringify (config.data)}}ReturN config},Error => {When / / request errorConsole.log ('request:', error)/ / 1. to judge request timeoutIf (error.code = = ='ECONNABORTED'& & error.message.indexOf ('timeout'))! = = = = -1) {Console.log ('timeout request timeout ")/ / return service.request (originalRequest); / / / / repeat request once}/ / 2. needs redirecting to the wrong pageConst errorInfo = error.responseConsOle.log (errorInfo)If (errorInfo) {//error =errorInfo.data / / catch can be obtained in detail when the page is over there.Wrong information, look at the bottom of the Promise.rejectConst errorStatus = errorInfo.status; / / 404403500...Router.push ({Path: `/error/${errorStatus}`})}Return PromIse.reject (error) / / on the other side of the call, you can get (CATCH) the error message you want to return.})/ / response interceptorInstance.inteRceptors.response.use (Response => {Let data;Response.data is undefin when / / IE9Ed, so you need to use response.request.responseText (string after Stringify).If (response.data = = undefined) {Data = JSON.parse (response.request.responseText)} else {Data = response.dATA}/ / / / to do different processing based on the returned code valueSwitch (data.rc) {Case 1:Console.log (data.desc)Break;Case 0:Store.commit ('changeState')/ / console.log ('login success')Default:}/ / if it is not correctly returned to code and is already logged in, it will throw an error./ / / const err = new Error (data.desc)/ / err.data = Data/ / err.response = reSponse/ / throw errReturn data},Err => {If (ERR & &a)Mp; err.response) {Switch (err.response.status) {Case 400:Err.message = 'request error'BreakCase 401:Err.message = 'unauthorized, please log in'BreakCase 403:Err.message = 'refusal access'BreakCase 404:Err.message = request address error: ${err.response.config.url}`BReakCase 408:Err.message = 'request timeout'BreakCase500:Err.message = 'server internal error'BreakCase 501:Err.message = 'service is not implemented'BreakCase 502:Err.message = 'gateway error'BreakCase 503:Err.message = 'service is not available'BreakCase 504:Err.message = 'gateway timeout'BreakCase 505:Err.message ='HTTP version is not supported 'BreakDefault:}}Console.error (ERR)Return Promise.reject (ERR) / / returns the error message returned by the interface.})/ / request processingInstance (options).Then (RES => {Resolve (RES)Return false}).Catch (Error => {Reject (error)})})}


import axios from './api'

/* Unify all the interfaces for maintenance* if the project is very large, URL can be made into files independently, and interfaces can be divided into different modules.* * // / / separate exportExport const query = () => {RetuRN Axios ({Url:'/query',Method:'get'})}Export const list = (ID) => {Return Axios ({Url: `/list${id}`,Method:'get'})}Export const upload = =Data => {Return Axios ({Url:'/upload',Method:'post',Data})}/ / default all exportExport default {Query,List,Upload}


Encapsulated into Vue plug-ins

// Importing all interfacesImport apiList from'./interface'Const install = Vue => {If (install.installed)Return;Install.installed = true;Object.defineProperties (Vue.prototype, {/ / /Note that this is mounted on the $api object of the Vue prototype.$api: {Get () {Return apiList}}})}Export default install


So far, everything is useless. Do the following in mian.js:

import api from './http/index'
// $api can be invoked on the Vue prototype directly at this time

Use in Vue

// List.vue

this.$api.list(id).then(res => {
     if (res.rc === 0) {
          this.pageList = res.data.item
      } else {
     .catch(error => {


  • The above two encapsulation is more comprehensive, basically completed our previous needs.
  • In error handling, you also need to return the value with the back-end agreement, making specific conventions.

this article is released in https://www.cssge.com at the same time.

Reference article

Link of this Article: Encapsulate Axios as a Vue plug-in

Leave a Reply

Your email address will not be published. Required fields are marked *