You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于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);
}

关键修正点

  1. 请求头名称对齐:Postman用的是Authentication头,你之前写成了Authorization,需统一为Authentication。
  2. axios参数结构修正:post方法的第三个参数是配置对象,headers必须放在{ headers }内部传递,不能直接传headers对象。
  3. 编码逻辑对齐:Postman中是将字符串转为Utf8字节流再转Base64,前端用encodeURIComponent处理后再转Base64,能避免直接用btoa处理非ASCII字符时的乱码或报错。
  4. 健壮性优化:添加了LocalStorage取值为空的默认处理,以及请求错误捕获。

内容的提问来源于stack exchange,提问作者Rickstrife

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 04:45:17