axios封装简单有效

一、新建一个axios文件夹
新建一个fetch.js文件:

关注我的微信公众号【前端基础教程从0开始】,加我微信,可以免费为您解答问题。回复“1”,拉你进程序员技术讨论群。回复“小程序”,领取300个优秀的小程序开源代码+一套入门教程。回复“领取资源”,领取300G前端,Java,微信小程序,Python等资源,让我们一起学前端。
import axios from ‘axios’;

const TENANT_ID='0'
const ENCRYPT_KEY='shrewshrewshrews'

export function fetch(url,method,params={}){
    //判断obj中的投放范围、类型、状态是否为空
    let newObjs={}
    let strs=''
    for(var item in params){
        if(params[item]!=''){
            strs= "newObjs."+item+"='"+params[item]+"'";
            eval(strs);
        }
    }
    this.body = Object.assign({
        randomStr: new Date().getTime().toString(),
        reqDate: formatData('yyyyMMdd'),
        reqTime: formatData('yyyyMMddhhmmss'),
        tenantId: TENANT_ID,
    }, newObjs);
    let sing=signatureTempGenerate(this.body)
    let sha256 = require("js-sha256").sha256
    console.log(sing)
    console.log(sha256(sing))//这就是你加密之后的密码
    this.body.signature = sha256(sing);
    this.params=this.body
    console.log(this.params)
    let data = method.toLocaleLowerCase() === 'get' ? 'params' : 'data';
    return new Promise((resolve,reject) => {
        axios({
            method,
            url,
            [data]: params, // 差异点在于data的值
            headers:{
                'TENANT_ID':'0',
                //'Authorization':'bearer '+this.access_token
            },
        })
        .then(response => {
            resolve(response.data);
        })
        .catch(err => {
            reject(err)
        })
    })
}
//签名
function signatureTempGenerate(data) {
    let keys = Object.keys(data).sort();
    let stringSignTemp = '';
    keys.forEach((key) => {
        if (!data[key] || key === 'password') return null;
        stringSignTemp = stringSignTemp
            ? `${stringSignTemp}&${key}=${data[key]}`
            : `${key}=${data[key]}`;
    });
    stringSignTemp = stringSignTemp
        ? `${stringSignTemp}&key=${ENCRYPT_KEY}`
        : `key=${ENCRYPT_KEY}`;
    return stringSignTemp;
}
function formatData (fmt = 'yyyy-MM-dd hh:mm:ss', date = new Date()) {
    let o = {
        "M+" : date.getMonth()+1,
        "d+" : date.getDate(),
        "h+" : date.getHours(),
        "m+" : date.getMinutes(),
        "s+" : date.getSeconds(),
        "q+" : Math.floor((date.getMonth()+3)/3),
        "S"  : date.getMilliseconds()
    };
    if(/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
    }
    for(let k in o) {
        if(new RegExp("("+ k +")").test(fmt)){
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        }
    }
    return fmt;
}

二、在main.js中挂载

import {fetch} from '../../axios/fetch'
//定义全局变量
Vue.prototype.$fetch=fetch;

三、在组件中使用

mounted(){
  this.$fetch(this.Ce_Host,'get',{
       format:'json',
       calback:'',
       from:'webapp_music',
       method:'baidu.ting.billboard.billList',
       type:1,
       size:10,
       offset:2
   })
   .then((res) => {
       console.log(res)
   })
   .catch(err => {
       console.log(err)
   })  
},

你可能感兴趣的:(axios封装简单有效)