微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SendGrid:设置环境变量不起作用

如何解决SendGrid:设置环境变量不起作用

我正在为我的网站创建一个联系表单,并且试图为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,next) => {
    res.send('API Status: Running');
});

app.post('/api/email',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
            });
        });
});

解决方法

首先在后端代码结构中创建一个.env文件 在里面声明SENDGRID_API_KEY ='YOUR API KEY' 这样,您将可以通过以下方式使用Sendgrid api密钥:

process.env.SENDGRID_API_KEY 
,

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

sendGrid.setApiKey(process.env.SENDGRID_API_KEY);

sendGrid.setApiKey('YOUR API KEY');

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。