首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Sendgrid API密钥无法从环境变量中正确读取

Sendgrid API密钥无法从环境变量中正确读取
EN

Stack Overflow用户
提问于 2020-06-13 05:42:24
回答 2查看 1.5K关注 0票数 0

我正在遵循Node.js上的Sendgrid (https://app.sendgrid.com/guide/integrate/langs/nodejs)的安装指南,但我一直收到一个API键错误。

这是我的代码:

代码语言:javascript
复制
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密钥:

代码语言:javascript
复制
SENDGRID_API_KEY=SG.oqKbQHcNxxxxxxxxxxxxxkY5B4o

这是我收到的错误消息:

代码语言:javascript
复制
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密钥设置为字符串,如下所示:

代码语言:javascript
复制
sgMail.setApiKey('SG.oqKbQHcNxxxxxxxxxxxxxkY5B4o')

然后它就起作用了。但很明显,出于安全原因,我不能把它留在这里。你知道它为什么会这样吗?我该怎么解决它?

EN

回答 2

Stack Overflow用户

发布于 2020-06-16 21:12:42

问题出在.env文件的位置。我的后端文件夹嵌套在另一个文件夹中,所以我必须将它移到实际的根目录中。

票数 0
EN

Stack Overflow用户

发布于 2021-07-29 22:04:11

从npm安装dotenv包,并使用这段代码来确保它接受.env文件:

代码语言:javascript
复制
if (process.env.NODE_ENV !== 'production') require('dotenv').config();

控制台记录process.env.SENDGRID_API_KEY,检查程序是否正在获取api密钥。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62352914

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档