【问题标题】:SendGrid: Setting Env Variable not workingSendGrid:设置环境变量不起作用
【发布时间】:2020-08-28 12:17:59
【问题描述】:

我正在为我的网站创建一个联系表单,并且我正在尝试为 SendGrid 设置环境变量,但它不起作用。

我已经尝试过setx SENDGRID_API_KEY 'SG.myAPIKey',但是当我运行代码时,它给了我消息“API 密钥不以“SG”开头。

如果有帮助,我有以下代码。

谢谢!

App.js

const express = require('express'); //Needed to launch server.
const bodyParser = require('body-parser');
const cors = require('cors'); //Needed to disable sendgrid security.
const sendGrid = require('@sendGrid/mail'); //Access SendGrid library to send emails.

sendGrid.setApiKey(process.env.SENDGRID_API_KEY);

//sendGrid.setApiKey('SG.myAPIKey');
const app = express(); //Alias from the express function.

app.use(bodyParser.json());

app.use(cors());

app.listen(4000, '0.0.0.0');

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    next();
});

app.get('/api', (req, res, next) => {
    res.send('API Status: Running');
});

app.post('/api/email', (req, res, next) => {
    console.log(req.body);
    const msg = {
        to: 'dyzhang@gatech.edu',
        from: req.body.email,
        subject: req.body.subject,
        text: req.body.message
    }
    sendGrid.send(msg)
        .then(result => {
            res.status(200).json({
                success: true
            });
        })
        .catch(err => {
            console.log('error: ', err);
            res.status(401).json({
                success: false
            });
        });
});

【问题讨论】:

  • process.env.SENDGRID_API_KEY 你的环境文件中有这个吗?
  • 没有?如何创建一个?

标签: node.js environment-variables sendgrid


【解决方案1】:

首先在您的后端代码结构中创建一个.env 文件 在里面声明 SENDGRID_API_KEY = 'YOUR API KEY' 这样你就可以使用 Sendgrid api 键了

process.env.SENDGRID_API_KEY 

【讨论】:

  • 如何创建.env文件?
  • 只需创建一个文件并将其命名为 .env,就像在项目中创建 server.js 或任何其他文件一样
【解决方案2】:

正如@jarivak 建议的那样,您需要创建一个.env 文件并使用 process.env.SENDGRID_API_KEY 但这是推荐的方式。 如果您希望它用于测试目的,只需更改此行

sendGrid.setApiKey(process.env.SENDGRID_API_KEY);

sendGrid.setApiKey('YOUR API KEY');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多