Teach you how to encapsulate general axios in vue project

Teach you how to encapsulate general axios in vue project


Tip: Here you can add the general contents to be recorded in this article:
For example, with the continuous development of artificial intelligence, machine learning technology is becoming more and more important. Many people have started learning machine learning. This paper introduces the basic content of machine learning.

Tip: the following is the main content of this article. The following cases can be used for reference

1, Why encapsulate axios?

  • Unified management base address
  • Processing requests and responses
  • It is convenient to send requests to the background server and reduce redundant code

Example: pandas is a NumPy based tool created to solve data analysis tasks.

2, Packaging steps

1. Install dependent packages

The code is as follows (example):

npm install axios

2. Start packaging

Note: the file name is customized. It is a common tool function under the utils directory.

Create a new request.js file in the src/utils directory

// Import axios
import axios from 'axios'
// Create an independent strength object. 1 may have multiple paths. 2 is easy to modify
const baseURL=''
const instance =axios.create({
export default (options)=>{
  return instance({
   // ES6 rule: the key of an object can be a dynamic variable
    [options.method.toUpperCase()==='GET'?'params' :'data']:option.data

Set request interceptor

import store from '@/store'  
  // Add request header uniformly 
  const token=store.state.user.profile.token
    //Login succeeded. Add token s uniformly
    config.headers.Authorization=`Bearer ${token}`
  return config
}, err=>{
   return Promise.reject(err)

Set response interceptor

import router from '@/router'
  // Remove a layer of data attribute from the returned data
    return res,data
}, err=>{
     // The token is invalid. Jump to landing page
      return   router.push('/login')
   return Promise.reject(err)


  • Create axios
  • Encapsulating common request methods
  • Configure relevant parameters to uniformly process request parameters
  • Request Interceptor: handle request header token
  • Response Interceptor: handle the returned data and token failure

3 how to use

Insert the code slice here and create a new index.js file in the src/api directory

import request from '@/utils/request.js'

  method: 'post', // Request mode
  url: '#', / / request address
  data: { // Request parameters
    account: 'admin',
    pwd: 123


1. Object access method

  • Object. Property name
  • Object [attribute name] = = = > benefits: attribute names can be variables

2. Dynamic key

  • There is such a piece of code in the encapsulated code. Let's explain it here.
  • According to the new es6 rules, the key of an object can be a dynamic variable
    [options.method.toUpperCase() === 'GET' ? 'params' : 'data']: options.data

Meaning of ternary expression in []:

When the incoming value is get, first capitalize the incoming value and compare it with the following values. If it is equal, the name of the key is params, otherwise it is data

  • Example display
const obj={
console.log(obj.msg) // hello
 const info='msg'
 console.log(obj[info]) // hello

const obj ={

const info =abc
const obj ={
console.log(obj)   // { msg:'hello', abc:'nihao'}

const obj ={
console.log(obj)   // { msg:'hello', info:'nihao'}

Keywords: Front-end Vue

Added by Trip1 on Sun, 12 Sep 2021 10:54:06 +0300