current position:Home>Vue encapsulates Axios to call interface Full Version (code source code) latest recommendation (II)

Vue encapsulates Axios to call interface Full Version (code source code) latest recommendation (II)

2022-04-29 07:26:05MFG_ six hundred and sixty-six

First take a look at the directory you need to create , There are mainly api , utils Of request.js , main.js , vue.config.js ,view below first.vue, Here's the picture

 Insert picture description here

1. Global installation axios

  1. Download plug-ins

npm install axios --save

2. And then in main.js Global mount

import axios from 'axios'
Vue.prototype.$axios = axios

2. establish api Below request.js This is the custom file name , The code is as follows

The document code is as follows :

import axios from 'axios'

// get request 

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

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


axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

//  Request interceptor 
axios.interceptors.request.use(function (config) {
    
  return config;
}, function (error) {
    
  return Promise.reject(error);
})
//  Response interceptors 
axios.interceptors.response.use(function (response) {
    
  return response;
}, function (error) {
    
  return Promise.reject(error);
})

//  encapsulation axios Of post request 
export function fetch(url, params) {
    
  return new Promise((resolve, reject) => {
    
    axios.post(url, params)
      .then(response => {
    
        resolve(response.data);
      })
      .catch((error) => {
    
        reject(error);
      })
  })
}

3. establish utils Below request.js This is the custom file name , The code is as follows

Pay attention to mainly add this : find baseURL: Need to ask for domain name add , .com ending , for example https://baidu.com/

Download this file below
npm install js-md5 --save
npm install element-ui --save

import axios from 'axios'
import {
     Notification, MessageBox, Message } from 'element-ui'
import store from '@/store'
import md5 from 'js-md5'

var getId = () => {
    
  return localStorage.getItem('userId');
}

var getToken = () => {
    
  return localStorage.getItem('token');
}

var showErr = true

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
//  establish axios example 
const service = axios.create({
    
  // axios The request configuration in is baseURL Options , To express a request URL Common part 
  baseURL: 'https://baidu.com',
  //  Overtime 
  timeout: 10000
})
// request Interceptor 
service.interceptors.request.use(config => {
    
  if (config && config.data && 'showErr' in config.data) {
    
    showErr = config.data.showErr
  }

  if (config.method === 'post' && !config.data) {
    
    config.data = {
    }
    config.data.aid = getId()
    config.data.t = new Date().getTime()
  } else if (config.method === 'post' && config.data) {
    
    config.data.aid = getId()
    config.data.t = new Date().getTime()
  }

  if (config.method === 'post') {
    
    config.transformRequest = (data, headers) => {
    
      let req = JSON.stringify(data)
      let token = getToken()
      let sign = md5(req + token)
      console.log(req + token)
      config.headers['sign'] = sign
      return req
    }
  }


  if (config.method === 'get' && !config.params) {
    
    config.params = {
    }
    config.params.accessToken = getToken()
    config.params.timeStamp = new Date().getTime()
  } else if (config.method === 'get' && config.params) {
    
    if (!config.params.accessToken) config.params.accessToken = getToken()
    config.params.timeStamp = new Date().getTime()
  }

  // get Request mapping params Parameters 
  if (config.method === 'get' && config.params) {
    
    let url = config.url + '?';
    for (const propName of Object.keys(config.params)) {
    
      const value = config.params[propName];
      var part = encodeURIComponent(propName) + "=";
      if (value !== null && typeof (value) !== "undefined") {
    
        if (typeof value === 'object') {
    
          for (const key of Object.keys(value)) {
    
            if (value[key] !== null && typeof (value[key]) !== 'undefined') {
    
              let params = propName + '[' + key + ']';
              let subPart = encodeURIComponent(params) + '=';
              url += subPart + encodeURIComponent(value[key]) + '&';
            }
          }
        } else {
    
          url += part + encodeURIComponent(value) + "&";
        }
      }
    }
    url = url.slice(0, -1);
    config.params = {
    };
    config.url = url;
  }
  return config
}, error => {
    
  console.log(error)
  Promise.reject(error)
})

//  Response interceptors 
service.interceptors.response.use(res => {
    
  //  If the status code is not set, the default status is success 
  const code = res.data.code;
  //  Get error messages 
  //const msg = i18n.t(`errCode.E${code}`)
  const msg = res.data.msg
  const flag = res.data.flag
  if (!flag && (code === 401 || code === 403)) {
    
    MessageBox.confirm(msg, ' Tips ', {
    
      confirmButtonText: ' determine ',
      cancelButtonText: ' Cancel ',
      type: 'warning'
    }
    ).then(() => {
    
      store.dispatch('LogOut').then(() => {
    
        this.$router.go(0)
      })
    }).catch(() => {
     });
    return Promise.reject(' Login expired , Please login again ')
  } else if (!flag) {
    
    if (showErr) {
    
      Message({
    
        message: msg,
        type: 'error'
      })
    }
    return Promise.reject(new Error(msg))
  } else {
    
    return res.data
  }
},
  error => {
    
    console.log('err' + error)
    let {
     message } = error;
    if (message == "Network Error") {
    
      message = ' Network error ';
    }
    else if (message.includes("timeout")) {
    
      message = ' Server connection timed out ';
    }
    else if (message.includes("Request failed with status code")) {
    
      message = ' Network error ' + message.substr(message.length - 3);
    }
    Message({
    
      message: message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
service.version = 'v1'

export default service

4. establish vue.config.js Of target Represents the requested domain name , Cross domain codes are as follows

module.exports = {
    
  publicPath: './',
  lintOnSave: false, 
  devServer: {
    
    port: 8089, //  Start port 
    open: false, //  Whether to automatically open the web page after startup 
    proxy: {
    
      '/api': {
    
        target: 'https://baidu.com', //
        secure: true, // Accept each other is https The interface of 
        ws: true, //  Is it enabled? websockets
        changeOrigin: true, // Whether it is allowed to cross 
        pathRewrite: {
    
          '^/api': '/' // Delegate your address to this  /api  Use this next when requesting /api To replace your address 
        },
      }
    },
  }
}

5. Page call usage

<template>
  <div>
  </div>
</template>

<script>
import {
     get } from '../../api/request'
export default {
    
 data(){
    
    return{
    
      menuList:[]
    }
  },
  mounted () {
    
    this.getList()
  },
  methods: {
    
    async getList () {
    
      try {
    
        // const { data } = await get('/api/menuList',{}) // {} Parameters to be passed 
        const {
     data: {
     list } } = await get('/api/menuList',{
    }) // {} Parameters to be passed 
        this.menuList = list
      } catch (error) {
    
        console.log(error);
      }
    },
  }
}
</script>

If you feel the article is good, remember to pay attention and collect , If there is something wrong, please correct it , If you need to reprint , Please indicate the source , Thank you very much !!!

copyright notice
author[MFG_ six hundred and sixty-six],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204290458555795.html

Random recommended