axios.interceptors.request.use(
config => {
//请求拦截
if (config.url.includes('/es')) {
const username = 'admin';
const pasw = 'IwdPkriZxAqpN0hV2qCx1HyQ_';
config.headers['Authorization'] = 'Basic' + ' ' + btoa(username + ':' + pasw);
}
return config;
},
error => {
return Promise.reject(error);
}
);
前端的base64加密和解密的使用方法,一个是加密:window.btoa(),一个是解密:window.atob()
var str = "hello";
var str64 = window.btoa("hello");
console.log("字符串是:"+str); //"hello"
console.log("经base64编码后:"+str64); //"aGVsbG8="
console.log("base64解码后:"+window.atob(str64));//"hello"
Basic Authorization 认证核心就是每次请求是都必须使用该用户的uasename和password。
使用Basic Authorization认证有他的优点和缺点。优点在于开发调试简单,利于发起方控制等,缺点就是需要传递username和password,存在很大安全隐患;修改了账户名和密码需要重新校验等。
注意:‘Basic’ + ’ ’ + btoa(username + ‘:’ + pasw)中的空格。