从 SendGrid .env 文件中获取 API_KEY (Node.js)

Getting the API_KEY from SendGrid .env file (Node.js)

我正在为我的个人项目之一使用 SendGrid(Node.js)。我按照集成指南设置我的 API KEY .env 文件如下:

echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env

我的问题是...每次 运行 在本地设置后端之前,我必须先 运行

source ./sendgrid.env

为了让 process.env.YOUR_API_KEY 在密钥所在的位置得到确认。 但是在将 sendgrid.env 文件重命名为 .env 之后,我不再需要 运行 来源了。

我就是这样称呼 API KEY

require('dotenv').config()

const { validationResult } = require('express-validator')
const Appointment = require('../models/Appointment')
const User = require('../models/User')
const sgMail = require('@sendgrid/mail')

sgMail.setApiKey(process.env.SENDGRID_API_KEY)

PS。我已经在文件顶部设置了 dotenv 配置,但在我更改文件名之前仍然未定义。

有人知道这背后的原因或逻辑吗?? 谢谢:)

如果我理解得足够好的话。您必须将其更改为 .env,因为默认情况下 require('dotenv').config() 指向 .env,因为配置的括号为空。 要通过调用您的文件 sendgrid.env 来遵循 sendgrid 方式,您必须 require('dotenv').config(sendgrid.env) 并且也许 require('dotenv').config(sendgrid) 就足够了。必须尝试一下才能确定。但至少根据我的理解,这是你的答案。