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
});
前端请求时加一个密钥的超详细方法
于 2022-08-11 12:40:56 首次发布