axios封装简单有效
一、新建一个axios文件夹新建一个fetch.js文件:import axios from ‘axios’;const TENANT_ID='0'const ENCRYPT_KEY='shrewshrewshrews'export function fetch(url,method,params={}){//判断obj中的投放范围、类型、状态是否为空let new...
·
一、新建一个axios文件夹
新建一个fetch.js文件:
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)
})
},
公众号:
微信:
更多推荐
已为社区贡献2条内容
所有评论(0)