node.js - Sendgrid API 密钥未从 env 变量中正确读取
问题描述
我正在关注 Node.js 上的 Sendgrid 设置指南(https://app.sendgrid.com/guide/integrate/langs/nodejs),但我不断收到 API 密钥错误。
这是我的代码:
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: 'test@example.com',
from: 'test@example.com',
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(() => console.log('send mail success'))
.catch(console.log);
我的 .env 文件中正确设置了我的 API 密钥:
SENDGRID_API_KEY=SG.oqKbQHcNxxxxxxxxxxxxxkY5B4o
这是我收到的错误消息:
API key does not start with "SG.".
ResponseError: Unauthorized
at BE-KeyCon/node_modules/@sendgrid/client/src/classes/client.js:133:29
at processTicksAndRejections (internal/process/task_queues.js:97:5) {
code: 401,
response: {
headers: {
server: 'nginx',
date: 'Fri, 12 Jun 2020 21:31:08 GMT',
'content-type': 'application/json',
'content-length': '116',
connection: 'close',
'access-control-allow-origin': 'https://sendgrid.api-docs.io',
'access-control-allow-methods': 'POST',
'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-of, x-sg-elas-acl',
'access-control-max-age': '600',
'x-no-cors-reason': 'https://sendgrid.com/docs/Classroom/Basics/API/cors.html'
},
body: { errors: [Array] }
}
}
如果我将 API 密钥设置为字符串,如下所示:
sgMail.setApiKey('SG.oqKbQHcNxxxxxxxxxxxxxkY5B4o')
然后它工作。但显然出于安全原因,我不能这样离开。知道为什么它会以这种方式运行以及如何解决它吗?
解决方案
从 npm安装dotenv
包并使用这段代码来确保它需要 .env 文件:
if (process.env.NODE_ENV !== 'production') require('dotenv').config();
控制台记录process.env.SENDGRID_API_KEY
以检查程序是否正在获取 api 密钥。
推荐阅读
- amazon-web-services - 如何在抓取 Amazon S3 文件夹时排除日期模式。使用 aws 爬虫
- c - C中的数据传输b/w服务器/客户端
- node.js - 如何解决升级 Node 版本后的问题
- python - 根据第二个索引的最大值删除列表中的元组
- c# - 如何使用 webApi 使用 woo 商务 webhook
- spring - GCP PostgreSQL 无缘无故收到快速关机请求,这是为什么呢?
- php - 将数据从api批量导入mysql数据库时超时错误laravel
- android - 与android studio的意图共享只显示图像而不是文本
- flutter - 处理拦截器中的 grpc 错误
- powershell - 进度条存在但不可见