从env变量中无法正确读取Sendgrid API密钥。

问题描述 投票:0回答:1

我正在按照Node.js上的Sendgrid的设置指南(https:/app.sendgrid.comguideintegratelangsnodejs。),但我一直得到一个API密钥错误。

这是我的代码。

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
  to: '[email protected]',
  from: '[email protected]',
  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);

我的API密钥在我的.env文件中被正确设置。

SENDGRID_API_KEY=SG.oqKbQHcNxxxxxxxxxxxxxkY5B4o

这是我得到的错误信息 This is the error message I'm getting:

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密钥设置成一个字符串 就像这样 If I set the API key as a string, like so:

sgMail.setApiKey('SG.oqKbQHcNxxxxxxxxxxxxxkY5B4o')

那就可以了 但很明显,出于安全考虑,我不能让它像这样。有什么办法可以解决这个问题吗?

node.js environment-variables sendgrid
1个回答
0
投票

问题在于.env文件的位置。我的后台文件夹嵌套在另一个文件夹里,所以我不得不把它移到实际的根目录下。

© www.soinside.com 2019 - 2024. All rights reserved.