Explain in detail the idea and method of Axios encapsulating API interface in Vue

  • 2021-08-28 19:21:45
  • OfStack

1. Encapsulation of axios

In the vue project, we usually use axios library for interacting with the background to obtain data, which is http library based on promise and can run in browser and node. js. It has many excellent features, such as intercepting requests and responses, canceling requests, transforming json, client defense XSRF and so on.

If we're going to use a lot of interfaces in a project, we can't have every page full of. get () or. post (), can we? Therefore, we have to manually encapsulate a global Axios network module, which is convenient and makes the code amount less redundant.

Installation


> npm install axios // This is the installation axios The command of 

First of all, we need to install Axios components in the project now. This step is 1.

After downloading, create two new directories in the src file of the project, one is http and one is api. The http directory is used to encapsulate the Axios, and the api directory is used to manage our interfaces.

Introduce

Step 1, first introduce axios into http. js


import axios from 'axios'

Switching of environment

When we develop a project, there will be many environments, such as development environment, test environment and production environment. Using axios. defaults. baseURL, we can set the default request address of axios.


// Testing in the development environment  development
if(process.env.NODE_ENV == 'development') {
 axios.defaults.baseURL = 'http://120.53.31.103:84/'
}
// Testing in a production environment  production
if(process.env.NODE_ENV == 'production') {
 axios.defaults.baseURL = 'https://wap.365msmk.com/'
}
// And 1 Species environment  debug

Set the response timeout

Set the default request timeout through axios. defaults. timeout. If the response time is exceeded, the user will be told that the current request has timed out, please refresh and so on


// Time for response timeout 
axios.defaults.timeout = 5000;

Setting Interface Request Interception


// Interface request interception 
axios.interceptors.request.use(
 config => {
 config.headers = { DeviceType : 'H5' } // Set the response header 
 return config
 }
)

Using promise to return the result of an axios request

post :


export function get(url,params){
 return new Promise((resolve,reject) => {
 axios.get(url,{
  params : params
 }).then(res => {
  resolve(res)
 }).catch(err => {
  reject(err)
 })
 })
}

get :


export function post(url,params){
 return new Promise((resolve,reject) => {
 axios.post(url,params)
 .then(res => {
  resolve(res.data)
 })
 .catch(err => {
  reject(err.data)
 })
 })
}

At this time, http. js is written. Next, go to api. js to get the api interface.

Now it's in api. js

The first is to introduce the newly packaged axios into api. js


import {get,post} from '../http/http.js'
//get post  At the same time, we must introduce 

Then you can get the data according to the interface document


// Method of encapsulating interface 
export function getAppIndex() {
 return get('api/app/recommend/appIndex')
}

export function getBanner() {
 return get('api/app/banner')
}

export function getTel() {
 return post('api/app/smsCode',{
  // What is used here is params Pass on the reference and write directly {} You can, you don't have to declare it again params La 
  mobile : 18567391972,
  sms_type : 'login'
 })
}

Then, you can go to the vue page to get data through the life cycle.

Again, if you don't decide 1, you must use async function. This is only one of the methods


async mounted() {
  //  Star lecturers, excellent courses and so on 
  let res = await getAppIndex();
  
  // Add to Array 
  this.startList = res.data.data.list
  
  //  Carousel chart list 
  var banner = await getBanner();
  // console.log(' Carousel chart '+ banner)
  if (banner.data.code == 200) {
  this.bannerList = banner.data.data
  }

  //  Mobile phone verification code interface 
  let Tel = await getTel();
  // console.log(' Mobile phone verification code '+ Tel)

  //
 },


Related articles: