Vue encapsulates axios to call interface full version (code source code) latest (3)

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,注意图片api下面的request.js更改为api.js文件名

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 api.js under the api This is a custom file name, the code is as follows

//登录接口
 export const authorization_service_users_login = 'api/authorization_service/users/login'

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>
    <button @click="login()"></button>
  </div>
</template>

<script>
import * as api from '../../api/api'
export default {
    
    
  data () {
    
    
    return {
    
    
      menuList: []
    }
  },
  mounted () {
    
    
    this.getList()
  },

  methods: {
    
    
    //登录方法
    login (loginFrom) {
    
    
      this.$refs.loginFormRef.validate(async (valid) => {
    
    
        if (valid) {
    
    
          request({
    
    
            method: "post",
            url: api.authorization_service_users_login,			// 引入api文件点api.js里面函数名字
            data: {
    
    
              account: this.loginFrom.account,	
              password: md5(this.loginFrom.password),
            },
          }).then((res) => {
    
    
            this.$message.success(this.$t("lang.message.loginSuccessful"));
            //保存登陆后的token状态
            window.localStorage.setItem("token", res.data.token);
            window.localStorage.setItem("account", res.data.account);
            // window.localStorage.setItem("username", res.dat);
            window.localStorage.setItem("userId", res.data.userId);
            // window.sessionStorage.setItem('userId',res.data.userId)
            this.$router.push("/home");
          });
        }
      });
    },
  }
}
</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/124472080