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

使用k6/http模块调用Gmail API遇401认证错误求助

问题分析与解决方案

核心错误

你调用Gmail API时对access token的引用存在错误:

  • 获取token的代码中,const accessToken = tokenResponse.json().access_token; 已经将返回的access_token字符串赋值给了accessToken变量。
  • 但构建请求头时,你写成了Authorization: Bearer ${accessToken.access_token},相当于在字符串变量上访问.access_token属性,结果必然是undefined,导致请求头的认证凭证无效,触发401错误。

修正后的代码

获取access token部分(无需修改)

const payload = `client_id=${clientId}&client_secret=${clientSecret}&refresh_token=${refreshToken}&grant_type=refresh_token`;
  
const tokenResponse = http.post(tokenUrl, payload, {
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
});
  
const accessToken = tokenResponse.json().access_token;

调用Gmail API部分(修正token引用)

const options = {
  url: 'https://gmail.googleapis.com/gmail/v1/users/test.tests@gmail.com/messages',
  params: {
    q: `from:no-reply@rework.link to:${profilesEmailAddress}`,
  },
  headers: {
    Authorization: `Bearer ${accessToken}`, // 直接使用已获取的token字符串
  },
};
const response = http.get(options.url, options.params, { headers: options.headers });

补充:k6的http.get第三个参数是配置对象,规范写法是将headers放在该对象内,避免潜在参数解析问题。

验证建议

调用API前可打印请求头内容,确认token是否正确:

console.log(`Authorization Header: Bearer ${accessToken}`);

确保打印的token与你在Postman中使用的有效token一致,排除token本身无效的可能性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 11:16:12