Vue encapsula axios para llamar a la versión completa de la interfaz (código fuente del código) más reciente (3)

Primero mire los directorios que deben crearse, incluidos principalmente api, request.js de utils, main.js, vue.config.js, first.vue debajo de la vista, como se muestra a continuación,注意图片api下面的request.js更改为api.js文件名

inserte la descripción de la imagen aquí

1. Instale axios globalmente

  1. Descargar complemento

npm install axios --save

2. Luego móntelo globalmente en main.js

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

2. Cree api.js bajo la API Este es un nombre de archivo personalizado, el código es el siguiente

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

3. Cree request.js en utils Este es un nombre de archivo personalizado, el código es el siguiente

Tenga en cuenta que la adición principal es esta : encuentre baseURL: agregue lo que debe solicitarse 域名, termine con .com, por ejemplo https://baidu.com/

El siguiente archivo también necesita ser descargado
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. El objetivo de crear vue.config.js representa el nombre de dominio solicitado, y el código de dominio cruzado es el siguiente

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. Uso de llamada de página

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

Si siente que el artículo es bueno, recuerde prestar atención, preste atención y recójalo. Corríjame si hay algún error. Si necesita reimprimir, indique la fuente, ¡gracias! ! !

Supongo que te gusta

Origin blog.csdn.net/m0_49714202/article/details/124472080
Recomendado
Clasificación