vue中axios的使用 和aes加密解密

axios

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。 axios文档

安装依赖

                npm install axios

                npm install vue-axios

main.js

import Vue from 'vue'
import App from './App.vue'
//elementUI
import './plugins/element.js'
import {  Message } from 'element-ui'
// import {  MessageBox } from 'element-ui'
import router from './router'

import axios from 'axios'
import VueAxios from 'vue-axios'


Vue.config.productionTip = false

axios.defaults.baseURL = 'http://123.com';

//添加请求时拦截器
axios.interceptors.request.use(config=>{
  //设置请求头为 表单提交头
  config.headers['Content-Type'] = "application/x-www-form-urlencoded"

  //设置提交数据为form表单格式
  let formData = new FormData()

  formData.append('p',JSON.stringify(config.data))

  config.data = formData
  
  console.log(config)

  return config
},err=>{
  return Promise.reject(err)
})

// 添加响应时拦截器
axios.interceptors.response.use(res=>{
  if(res.data.code == 200){
    return res
  }else{
    Message({type:'error',message:res.data.msg})
    return res
  }
  
},err=>{
  console.log(err)
})

//把axios注册到vue
Vue.use(VueAxios,axios)

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

login.vue  使用axios发送请求

<template>
  <div class="Login">
      <div class="top">
          <img src="../assets/logo1.png" alt="">
          <div>
              xx管理系统
          </div>
      </div>
      <div class="c-box">
          
        <div class="b-left">
        1111111
        </div>
        <div class="b-right">
            <div class="u-login">
                <div class="u-title">管理员登录</div>
                <el-form class="u-form" ref="form" :model="form" label-width="0px">
                    <el-form-item label="">
                        <el-input v-model="form.name" placeholder="请输入管理员账号"></el-input>
                    </el-form-item>
                    <el-form-item label="">
                        <el-input type="password" v-model="form.password" placeholder="请输入管理员密码"></el-input>
                    </el-form-item>
                    <el-button class="f-button" size="small" @click="login()" type="success">登录</el-button>
                </el-form>
            </div>
            
        </div>
        
      </div>
  </div>
</template>

<script>
// @ is an alias to /src
export default {
  name: 'Login',
  data(){
      return{
          form:{
              name:'',
              password:''
          }
      }
  },
  methods:{
      login(){
           //使用axios
          this.axios.post('/?s=App.DoLogin',{
            //   service:'App.Admin.DoLogin',
              username:this.form.name,
              password:this.form.password
          })
          .then(res=>{
            //   this.$message(res.data.msg)
              console.log(res)
          })
          .catch(err=>{
              console.log(err)
          })
      }
  }
}
</script>
<style scoped>
html,body{
    background:#4EB88C;
    width:100vw;
    height:100vh;
}
.Login{
    /* display: flex;
    justify-content: center;
    align-items:center;     */
    background:#4EB88C;
    width:100vw;
    height:100vh;
}
.top{
    width:100%;
    background:#ffffff;
    border-bottom:1px solid #f9f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding:15px 40px;
    box-sizing:border-box;
    font-size:20px;
    color:#494949;
    box-shadow:0px 3px 10px #999999;
}
.top img{
    width:100px;
    height:40px;
}

.c-box{
    display:flex;
    justify-content:space-between;
    align-items: center;
    width:60vw;
    height:80vh;
    margin:0 auto;
}
.b-left{
    height:60vh;
    background:#c9c9c9;
    flex: 1;

}
.b-right{
    height:500px;
    width:20vw;
    background:#ffffff;
    box-shadow:0px 0px 15px #696969;
}
.u-title{
    color:#4EB88C;
    text-align: center;
    border-bottom: 1px solid #747474;
    width:80%;
    margin:0 auto;
    font-weight: bold;
    font-size:20px;
    padding:15px 0;
}
.u-form{
    width:80%;
    margin:10px auto;
    text-align: center;
    margin-top:30px;
}
.u-form .f-button{
    background:#4EB88C;
    width:100% !important;
    margin-top:16px;
}
</style>

AES加密解密使用

更多细节:十分钟读懂AES加密算法 

安装依赖   npm install crypto-js

main.js

import Vue from 'vue'
import App from './App.vue'

import './plugins/element.js'
import {  Message } from 'element-ui'
// import {  MessageBox } from 'element-ui'

import router from './router'

import axios from 'axios'
import VueAxios from 'vue-axios'

// aes加密解密
import AES from './plugins/AES.js'

Vue.config.productionTip = false

axios.defaults.baseURL = 'http://123.com';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';


//添加请求时拦截器
axios.interceptors.request.use(config=>{

  //设置请求头为 表单提交头
  config.headers['Content-Type'] = "application/x-www-form-urlencoded"


  // AES 加密
  var encrypts = AES.encrypt(JSON.stringify(config.data))
  // //AES 解密
  // let de = JSON.parse(AES.decrypt(encrypts))
  // console.log('解密:', de)

  //设置提交数据为form表单格式
  let formData = new FormData()

  formData.append('p',encrypts)
  // formData.append('p',JSON.stringify(config.data))

  config.data = formData
  
  console.log(config)

  return config
},err=>{
  return Promise.reject(err)
})


// 添加响应时拦截器
axios.interceptors.response.use(res=>{

  if(res.data.code == 200){
    //AES 解密
    let de = AES.decrypt(res.data)
    console.log('解密:', de)
    res.data = de
    return res
  }else{
    Message({type:'error',message:res.data.msg})
    return res
  }
  
},err=>{
  console.log(err)
})


Vue.use(VueAxios,axios)

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

AES.js

import CryptoJS from 'crypto-js';
const iv = '2099475638181938'
const keyStr = '1556896841231548'
 
export default {
    //随机生成指定数量的16进制key
    generatekey(num) {
        let library = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        let key = "";
        for (var i = 0; i < num; i++) {
            let randomPoz = Math.floor(Math.random() * library.length);
            key += library.substring(randomPoz, randomPoz + 1);
        }
        return key;
    },
    
    //加密
    encrypt(word) {
        var key = CryptoJS.enc.Utf8.parse(keyStr);
        var srcs = CryptoJS.enc.Utf8.parse(word);
        var encrypted = CryptoJS.AES.encrypt(srcs, key, { iv:CryptoJS.enc.Utf8.parse(iv), mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
        return encrypted.toString();
    },
    //解密
    decrypt(word) {
        var key = CryptoJS.enc.Utf8.parse(keyStr);
        var decrypt = CryptoJS.AES.decrypt(word, key, { iv:CryptoJS.enc.Utf8.parse(iv), mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
        return CryptoJS.enc.Utf8.stringify(decrypt).toString();
    }
 
}

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
axios 是一个基于 Promise 的 HTTP 客户端,可以用于浏览器和 Node.js。而 AES(Advanced Encryption Standard)是一种常用的对称加密算法,可以用来加密解密数据。 在 VUE3 项目使用 axiosAES 进行加密解密的步骤如下: 1. 安装 axios 和 crypto-js: ```bash npm install axios crypto-js ``` 2. 在需要使用 axios 的组件或页面引入 axios 和 crypto-js: ```javascript import axios from 'axios'; import CryptoJS from 'crypto-js'; ``` 3. 定义一个加密函数,用来对请求数据进行加密: ```javascript function encryptData(data, key) { const iv = CryptoJS.enc.Utf8.parse('1234567890123456'); // 初始化向量 const encrypted = CryptoJS.AES.encrypt(data, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }); return encrypted.toString(); } ``` 其,`data` 是需要加密的数据,`key` 是加密密钥,`iv` 是初始化向量,`mode` 和 `padding` 是 AES 加密算法的模式和填充方式。 4. 在发送请求前,对请求数据进行加密: ```javascript const key = '1234567890123456'; // 加密密钥 const requestData = { name: 'John', age: 30 }; // 需要加密的数据 const encryptedData = encryptData(JSON.stringify(requestData), key); // 对数据进行加密 axios.post('/api/data', { data: encryptedData }) .then(response => { console.log(response.data); }) .catch(error => { console.error(error); }); ``` 其,`JSON.stringify(requestData)` 将请求数据转换成字符串,然后使用 `encryptData` 函数对其进行加密。 5. 定义一个解密函数,用来对响应数据进行解密: ```javascript function decryptData(data, key) { const iv = CryptoJS.enc.Utf8.parse('1234567890123456'); // 初始化向量 const decrypted = CryptoJS.AES.decrypt(data, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }); return decrypted.toString(CryptoJS.enc.Utf8); } ``` 其,`data` 是需要解密的数据,`key` 是解密密钥,`iv` 是初始化向量,`mode` 和 `padding` 是 AES 解密算法的模式和填充方式。 6. 在接收响应后,对响应数据进行解密: ```javascript const key = '1234567890123456'; // 解密密钥 axios.get('/api/data') .then(response => { const decryptedData = decryptData(response.data, key); // 对响应数据进行解密 console.log(JSON.parse(decryptedData)); }) .catch(error => { console.error(error); }); ``` 其,`response.data` 是响应数据,使用 `decryptData` 函数对其进行解密,然后使用 `JSON.parse` 将解密后的字符串转换成对象。 注意:在使用 AES 加密算法时,加密密钥和解密密钥必须相同,否则无法正确解密数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xuhang139

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值