zoukankan      html  css  js  c++  java
  • vue 封装axios api模块化 并使用方式 MD5 数据加密

    为了方便使用 axios 将其封装

    httpService.js

    import axios from 'axios' // 引入axios
    import { Loading , Message } from 'element-ui' // 引入Elemente-ui (根据自己使用的UI框架引入 )
    const BASE_URL = process.env.BASE_API // 获取全局设置的请求地址
    // 定义get请求 数据处理函数 json对象 转字符串
    const formatParams = (data) => {
      let arr = []
      for (let name in data) {
        arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]))
      }
      return arr.join('&')
    }
    axios.defaults.timeout = 15000 // 设置请求超时时间
    /**
     * 请求时拦截
     */
    axios.interceptors.request.use(config => {
    // 发送请求时设置头部数据
    // if (Vuevm.$store.getters.token) { // config.headers.common['authorization'] = // Vuevm.$store.getters.token // } return config }, error => { return Promise.reject(error.response) }) /** * 数据返回拦截 */ axios.interceptors.response.use(function (response) {
    // 获取服务端返回的头部数据
    // if (response.headers.authorization) { // Vuevm.$store.commit('token', response.headers.authorization) // } return response }, function (error) { return Promise.reject(error) }) // 设置请求处理函数 (get,post,put) export const httpService = (url, params, method, loading=true) => { let loadingInstance = null console.log(BASE_URL + url) if (loading) { loadingInstance = Loading.service({ lock: true, text: '加载中', spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)" }) } if (method === 'post') { return new Promise((resolve, reject) => { axios.post(BASE_URL + url, params).then(data => { if (loading) loadingInstance.close() resolve(data.data) }).catch(error => { if (loading) loadingInstance.close() Message.error('网络不给力') reject(error) }) }) } else if (method === 'get') { return new Promise((resolve, reject) => { axios.get(BASE_URL + url + '?' + formatParams(params)).then(data => { if (loading) loadingInstance.close() resolve(data.data) }).catch(error => { if (loading) loadingInstance.close() Message.error('网络不给力') reject(error) }) }) } else if (method === 'put') { return new Promise((resolve, reject) => { axios.put(BASE_URL + url + '?' + formatParams(params)).then(data => { if (loading) loadingInstance.close() resolve(data.data) }).catch(error => { if (loading) loadingInstance.close() Message.error('网络不给力') reject(error) }) }) } }

    创建member.js (定义api模块 方便接口统一管理)

    import { httpService } from './httpService' // 引入httpService
    /**
     * @name 代理用户列表
     * @param {*} params
     */
    export const agencyList = (params) => {
      return httpService('/web/user/list/agency', params, 'get')
    }

    页面使用

    import { agencyList } from '@/api/member' // 引入定义的api模块 获取对应的函数
    // 定义请求接口函数 使用async 异步
    async getList () {
          const listData = await agencyList(this.form)
          console.log(listData)
    }

    axios MD5 加密 封装

    import axios from 'axios'
    import Qs from 'qs'
    import { appKey , calcuMD5 , decryptBy , encryptBy } from '../config'
    window.Vuevm = Vuevm;
    const BASE_URL = process.env.BASE_API //域名路径
    const SEEDMD5 = calcuMD5("U2FsdGVkX189N3VRCrUckSMoQM98v8PB") //加密MD5
    
    const formatParams = (data)=>{
        let arr = [];
        for (let name in data) {
            arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]))
        }
        return arr.join("&")
    }
    
    axios.defaults.timeout = 15000 //超时时间
    
    export const httpService = (url,params,method,loading=true) => {
        let slol = JSON.stringify(params)
        let data = encryptBy(slol, SEEDMD5)//加密参数
        let t = Date.parse(new Date())//时间戳
        let fString = appKey + "&" + t + "&" + data
        let sign = encryptBy(fString, SEEDMD5)
    
        let newParams = {
            data,
            appKey,
            t,
            sign,
            token: window.localStorage.token?window.localStorage.token:''
        }
        
        if(method === 'post')
        {
            return new Promise((resolve, reject) => { 
                axios.post(BASE_URL+url, Qs.stringify(newParams),{
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                    }).then(data=>{
              // 获取到的数据进行解密 data.data
    = JSON.parse(decryptBy(data.data,calcuMD5("U2FsdGVkXN32VRRCrUckSMoQM98v8PBHUHA"))) resolve(data.data) }).catch(error=>{ reject(error) }) }) } }

    config.js

    import CryptoJS from 'crypto-js'
    import md5 from 'js-md5'
    export const appKey = 'cb6015828a44b5234ce9ed1c3bc7acb0'
    
    export const calcuMD5 = (pwd) => { return md5(pwd) }
    export const version = '1.0.1'
    export const gaoDerKey = 'fee31a04c1acd1c809cb4b4958673864'
    export const wxSecret = '4b200551ebef203582268ed45f149ada'
    export const wxAppId = 'wxeacc6d8f0388b30c'
    // MD5 加密 export const encryptBy =(plaintText,CRYPTOJSKEY) =>{ var plaintText = plaintText; var options = { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }; var key = CryptoJS.enc.Utf8.parse(CRYPTOJSKEY); var encryptedData = CryptoJS.DES.encrypt(plaintText, key, options); var encryptedBase64Str = encryptedData.toString(); return encryptedBase64Str; } export const decryptBy = (encryptedBase64Str,CRYPTOJSKEY, type) => { var encryptedBase64Str = encryptedBase64Str; var options = { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }; var key = CryptoJS.enc.Utf8.parse(CRYPTOJSKEY); // 解密 var decryptedData = CryptoJS.DES.decrypt(encryptedBase64Str, key, options); // 解密后,需要按照Utf8的方式将明文转位字符串 var decryptedStr = decryptedData.toString(CryptoJS.enc.Utf8); return decryptedStr; }
  • 相关阅读:
    线性表之顺序表的结构与实现
    (转)面试题1:第一个只出现一次的字符
    c++ 虚基类应用
    c++ 多重继承
    c++ 单继承派生类的构造函数
    c++ 构造函数
    深入 Struts2 的配置
    c++ 结构体
    深入浅出C指针
    HTML5 小实例
  • 原文地址:https://www.cnblogs.com/wukongz/p/13524349.html
Copyright © 2011-2022 走看看