Teach you how to encapsulate general axios in vue project

Teach you how to encapsulate general axios in vue project

preface

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({
  baseURL:baseURL
})
export default (options)=>{
  return instance({
    method:option.method||'GET',
    url:options.url,
   // 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'  
instance.interceptors.request.use(config=>{
  // Add request header uniformly 
  const token=store.state.user.profile.token
  if(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'
instance.interceptors.response.use(config=>{
  // Remove a layer of data attribute from the returned data
    return res,data
}, err=>{
  if(err.response&&err.response.status===401){
     // The token is invalid. Jump to landing page
      return   router.push('/login')
  }
   return Promise.reject(err)
})

Conclusion:

  • 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'

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

extend

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={
  msg:'hello'
}
console.log(obj.msg) // hello
 const info='msg'
 console.log(obj[info]) // hello

const obj ={
  msg:'hello'
}
console.log(obj)

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

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

Keywords: Front-end Vue

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