前端请求时加一个密钥的超详细方法

import axios from 'axios';
import { Base64 } from 'js-base64';
let md5 = require('js-md5');
const access_key = '{access_key}';  // 服务端生成的 access_key
const secret_key = '{secret_key}';  // 服务端生成的 secret_key

const timestamp = Date.parse(new Date()) / 1000;    // 取时间戳
const randomStr = (len) => {
	let str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	 let result = "";
	while(len) {
		let index = Math.floor(Math.random() * str.length);
		result += str[index];
		--len;
		
	}
	return result;
	
}

const echostr = randomStr(8);      // 随机字符串自行生成

const header = Base64.encode(JSON.stringify({
                   "alg": "md5",
                   "type": "jwt"
               }));
const payload = Base64.encode(JSON.stringify({
                 "timestamp": timestamp,
                 "echostr": echostr,
                 "ak": access_key
             }));
const signature_string = header  + '.' + payload;

function md5Sign(string, secret){
    return md5(string + secret);    // md5 库自行引入
}

const api_token = signature_string + '.' + md5Sign(signature_string,secret_key);

const requestConfig = {
    headers: {
        "api-token": api_token
    }
};

//请求时
axios.post('/api/example',{},requestConfig).then(res=>{
    // todo
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值