Node.js集成SendGrid遇API Key undefined及格式错误求助
SendGrid Node.js集成:API Key未加载及格式错误问题
问题概述
我正在按照SendGrid的Node.js集成指南操作,运行代码时出现两个问题:
console.log(process.env.SENDGRID_API_KEY)输出undefined- 收到错误提示:
API key does not start with "SG."
环境与代码信息
- 环境变量文件内容:[已移除API密钥]
- index.js代码(完全复制自SendGrid官方教程):
console.log(process.env.SENDGRID_API_KEY) const sgMail = require('@sendgrid/mail'); sgMail.setApiKey(process.env.SENDGRID_API_KEY); const msg = { to: 'evan.dickinson.flinn@gmail.com', from: 'improvedpts@improvedpts.com', // Use the email address or domain you verified above subject: 'Sending with Twilio SendGrid is Fun', text: 'and easy to do anywhere, even with Node.js', html: '<strong>and easy to do anywhere, even with Node.js</strong>', }; sgMail .send(msg) .then(() => {}, error => { console.error(error); if (error.response) { console.error(error.response.body) } });
- 项目文件夹包含文件:
index.js、package.json
错误信息
API key does not start with "SG.".
已尝试操作与需求
- 曾尝试引入dotenv但无效,恢复教程写法后,网上的解决方案均不生效
- 需求:让API成功发送邮件
解决方案
1. 正确配置并加载dotenv
- 安装依赖:
npm install dotenv - 在
index.js的最顶部添加加载代码(必须在其他require之前):require('dotenv').config(); - 检查
.env文件格式:- 文件命名必须是
.env(开头带点),放在项目根目录 - 内容格式为
SENDGRID_API_KEY=SG.xxxxxx(不要加引号,键值对之间不要有空格)
- 文件命名必须是
2. 验证API密钥有效性
- 登录SendGrid后台,确认复制的API密钥是以
SG.开头的完整字符串,不要遗漏字符或多带空格 - 临时硬编码密钥测试(测试后立即删除,禁止提交到代码仓库):
若此方法能成功发送邮件,说明问题出在环境变量加载环节。sgMail.setApiKey('SG.xxxxxx你的完整密钥xxxxxx');
3. 检查运行命令的环境变量传递
- 若使用package.json的scripts运行,修改脚本为:
然后执行"scripts": { "start": "node -r dotenv/config index.js" }npm start运行代码
4. 排查环境变量加载失败的其他原因
- 确认
.env文件确实在项目根目录,没有被误放位置 - 检查系统环境变量是否存在同名的
SENDGRID_API_KEY,避免本地配置被覆盖 - 重启终端后再运行代码,清除终端缓存的旧环境变量
内容的提问来源于stack exchange,提问作者Evan Dickinson
相关产品推荐
相关产品推荐

