使用Node.js @sendgrid/client调用SendGrid API v3返回未授权问题排查
SendGrid API v3 未授权问题排查
问题描述
使用Node.js的@sendgrid/client调用SendGrid API v3的/suppressions接口时,始终返回未授权错误,但同一API密钥在同一段代码中使用@sendgrid/mail发送邮件完全正常。即使创建全新的全权限API密钥,问题依然存在;而用相同密钥在Postman中发起完全一致的请求却能成功执行。
代码示例:
sgApiKey = config.get('sendGrid_APIKey'); sgClient.setApiKey(sgApiKey); const email = "test@abc.com"; const headers = { "on-behalf-of": "The subuser's username. This header generates the API call as if the subuser account was making the call." }; const request = { url: `/v3/asm/suppressions/global/${email}`, method: 'GET', headers: headers } sgClient.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) .catch(error => { console.error(error); });
原以为发送邮件的API密钥具备调用/suppressions接口的权限,但实际并非如此,请问问题出在哪里?
解决方案
- 修正或移除
on-behalf-of请求头:你代码中这个请求头的值是官方注释文本,并非真实的子用户账号名。如果不需要以子用户身份发起请求,直接删除该头即可;若需操作子用户数据,替换为实际的子用户用户名。 - 调整请求URL格式:尝试去掉URL开头的斜杠,改为
v3/asm/suppressions/global/${email},避免客户端路径拼接时出现异常。 - 确认密钥权限(可选):虽然Postman能正常调用,仍可核对API密钥是否开启了
Suppressions相关权限(如Suppressions Read),排除权限配置遗漏的可能。
内容的提问来源于stack exchange,提问作者Brett Parkhurst
相关产品推荐
相关产品推荐

