Vue encapsulates axios to call the interface full version (code source code) latest recommendation (2)

First look at the directories that need to be created, mainly including api, request.js of utils, main.js, vue.config.js, first.vue under the view, as shown below

insert image description here

1. Install axios globally

  1. Download plugin

npm install axios --save

2. Then mount it globally in main.js

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

2. Create request.js under the api. This is a custom file name. The code is as follows

The file code is as follows:

import axios from 'axios'

// get请求

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

// post请求
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'

// 请求拦截器
axios.interceptors.request.use(function (config) {
    
    
  return config;
}, function (error) {
    
    
  return Promise.reject(error);
})
// 响应拦截器
axios.interceptors.response.use(function (response) {
    
    
  return response;
}, function (error) {
    
    
  return Promise.reject(error);
})

// 封装axios的post请求
export function fetch(url, params) {
    
    
  return new Promise((resolve, reject) => {
    
    
    axios.post(url, params)
      .then(response => {
    
    
        resolve(response.data);
      })
      .catch((error) => {
    
    
        reject(error);
      })
  })
}

3. Create request.js under utils This is a custom file name, the code is as follows

Note that the main addition is this : find baseURL: add what needs to be requested 域名, end with .com, for example https://baidu.com/

The following file also needs to be downloaded
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'
// 创建axios实例
const service = axios.create({
    
    
  // axios中请求配置有baseURL选项,表示请求URL公共部分
  baseURL: 'https://baidu.com',
  // 超时
  timeout: 10000
})
// request拦截器
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请求映射params参数
  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)
})

// 响应拦截器
service.interceptors.response.use(res => {
    
    
  // 未设置状态码则默认成功状态
  const code = res.data.code;
  // 获取错误信息
  //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, '提示', {
    
    
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
    ).then(() => {
    
    
      store.dispatch('LogOut').then(() => {
    
    
        this.$router.go(0)
      })
    }).catch(() => {
    
     });
    return Promise.reject('登录已过期,请重新登陆')
  } 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 = '网络错误';
    }
    else if (message.includes("timeout")) {
    
    
      message = '服务器连接超时';
    }
    else if (message.includes("Request failed with status code")) {
    
    
      message = '网络错误' + message.substr(message.length - 3);
    }
    Message({
    
    
      message: message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
service.version = 'v1'

export default service

4. The target of creating vue.config.js represents the requested domain name, and the cross-domain code is as follows

module.exports = {
    
    
  publicPath: './',
  lintOnSave: false, 
  devServer: {
    
    
    port: 8089, // 启动端口
    open: false, // 启动后是否自动打开网页
    proxy: {
    
    
      '/api': {
    
    
        target: 'https://baidu.com', //
        secure: true, //接受对方是https的接口
        ws: true, // 是否启用websockets
        changeOrigin: true, //是否允许跨越
        pathRewrite: {
    
    
          '^/api': '/' //将你的地址代理位这个 /api 接下来请求时就使用这个/api来代替你的地址
        },
      }
    },
  }
}

5. Page call use

<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',{}) // {}需要传的参数
        const {
    
     data: {
    
     list } } = await get('/api/menuList',{
    
    }) // {}需要传的参数
        this.menuList = list
      } catch (error) {
    
    
        console.log(error);
      }
    },
  }
}
</script>

If you feel that the article is good, remember to pay attention, pay attention and collect it. Please correct me if there is any mistake. If you need to reprint, please indicate the source, thank you! ! !

Guess you like

Origin blog.csdn.net/m0_49714202/article/details/124471923