【问题标题】:Getting the API_KEY from SendGrid .env file (Node.js)从 SendGrid .env 文件 (Node.js) 获取 API_KEY
【发布时间】:2020-06-04 11:34:16
【问题描述】:

我将 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 配置,但在更改文件名之前仍然未定义。

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

【问题讨论】:

    标签: environment-variables sendgrid environment api-key dotenv


    【解决方案1】:

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

    【讨论】:

    • 嘿!你是对的,这就是问题所在。我将代码更改为require('dotenv').config({ path: '.sendgrid.env' }),它可以工作。谢谢 :) 以下是任何可能对此问题感兴趣的人的文档:npmjs.com/package/dotenv
    • 不错的补充!我将检查它以获取有关该主题的更多信息。
    猜你喜欢
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 2022-12-26
    • 2021-10-25
    • 1970-01-01
    • 2021-03-29
    相关资源
    最近更新 更多