如何基于LocalStorage中的Token生成API请求Basic认证头?
前端实现Postman认证头生成逻辑的正确方式
需求说明
需要为所有API请求生成自定义认证头,已有Postman预请求脚本实现该逻辑,现在要在前端通过axios复刻:从LocalStorage获取TokenHead和TokenTail,生成符合要求的认证头并发起请求。
Postman原实现代码
var Authentication = ""; Authentication += pm.collectionVariables.get( "TokenHead" ); Authentication += "." + pm.collectionVariables.get( "TokenTail" ); Authentication = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse( Authentication )); pm.request.headers.add("Authentication: basic " + Authentication );
你当前的前端代码
const TokenHead = localStorage.getItem('TokenHead'); const TokenTail = localStorage.getItem('TokenTail'); const Authentication = `${TokenHead}.${TokenTail}`; const EncodedAuthentication = btoa(Authentication); const headers = { 'Content-Type': 'application/json', Authorization: `Basic ${EncodedAuthentication}`, }; await axios .post(vURL, vData, headers) .then((vResponse) => { vStatus = vResponse.data.Status; });
修正后的正确实现
你的代码存在几个关键问题,修正后如下:
// 从LocalStorage获取参数,处理为空的情况 const tokenHead = localStorage.getItem('TokenHead') || ''; const tokenTail = localStorage.getItem('TokenTail') || ''; // 拼接字符串,对齐Postman的Utf8转Base64逻辑 const authStr = `${tokenHead}.${tokenTail}`; // 处理Utf8编码后转Base64,避免非ASCII字符报错 const encodedAuth = btoa(encodeURIComponent(authStr).replace(/%([0-9A-F]{2})/g, (match, p1) => String.fromCharCode('0x' + p1) )); // 构造请求头:注意头名称是Authentication,和Postman保持一致 const headers = { 'Content-Type': 'application/json', Authentication: `basic ${encodedAuth}` }; // axios请求:第三个参数是配置对象,headers需放在内部 try { const response = await axios.post(vURL, vData, { headers }); vStatus = response.data.Status; } catch (error) { console.error('请求失败:', error); }
关键修正点
- 请求头名称对齐:Postman用的是
Authentication头,你之前写成了Authorization,需统一为Authentication。 - axios参数结构修正:post方法的第三个参数是配置对象,headers必须放在
{ headers }内部传递,不能直接传headers对象。 - 编码逻辑对齐:Postman中是将字符串转为Utf8字节流再转Base64,前端用
encodeURIComponent处理后再转Base64,能避免直接用btoa处理非ASCII字符时的乱码或报错。 - 健壮性优化:添加了LocalStorage取值为空的默认处理,以及请求错误捕获。
内容的提问来源于stack exchange,提问作者Rickstrife
相关产品推荐
相关产品推荐

