在Heroku上部署时sendGrid无法正常工作

时间:2019-09-11 15:53:09

标签: javascript node.js reactjs heroku sendgrid

部署后,我在 heroku sendgrid 之间遇到了一些问题,我无法从表单发送电子邮件,在localhost中一切正常,但是在实时版本中有一个400错误的要求,有人对发生的事情有任何想法吗?

我已经尝试过:在我的配置中,我设置了所有SENDGRID_API_KEY,例如此处所示

https://devcenter.heroku.com/articles/sendgrid#provisioning-the-add-on

1)heroku插件:创建sendgrid:starter

2)设置SENDGRID_API_KEY并重新启动⬢gammefive ...完成,v18

逐步进行但仍无法正常工作,有些东西我看不到。 在本地,我在收件箱中看到我的电子邮件,一切正常100%正常

非常感谢您

const router = express.Router();
const sgMail = require('@sendgrid/mail');



router.post('/api/contact', async (req, res) => {


    sgMail.setApiKey(process.env.SENDGRID_API_KEY);

    const email = req.body.email;
    const name = req.body.name;
    const message = req.body.message;

    const msg = {
        to: process.env.GAMMEFIVE_EMAIL,
        from: email,
        subject: 'Email from gammefive',
        text: `name: ${name};
         email:${email}; message:${message}`
    };

    await sgMail
        .send(msg)
        .then(result => {
            res.status(200).send(result);
        })
        .catch(error => {
            res.status(400).send(error);
        });
});

module.exports = router; ```


**FRONT-END**

  sendData = async e => {

    const { name, email, message } = this.state;

    e.preventDefault();

    const data = {
      name,
      email,
      message
    };

      await axios
        .post("/api/contact", data)
        .then(res => {
          if (res.status === 200) {
            this.setState({
              alertMessage: ""
            });
          }
        })
        .catch(error => {
          console.log("important error", error);
        });

  };

2 个答案:

答案 0 :(得分:0)

我发现了问题,我遵循了https://devcenter.heroku.com/articles/sendgrid#provisioning-the-add-on 从文档中看,一切正常,但主要问题是(用普通英语说)heroku出于明显原因无法识别.env文件: GITIGNORE 文件,所以我在stackoverflow上找到了另一个答案从这里How do I deploy to heroku from git when my API key is in a .gitignore file?

我按照该答案中的步骤进行操作,关键是安装软件包https://github.com/xavdid/heroku-config 不要安装答案中的软件包。在安装后安装heroku plugins:install heroku-config,只需运行$ heroku config:push 并且您应该开始发送电子邮件。

我希望这对面临相同情况的人有用。

答案 1 :(得分:0)

您应该在heroku中设置 config vars

heroku配置set: {key}:{value}

以您的情况

heroku配置集:SENDGRID_API_KEY:YOUR_API_KEY

推送您的更改。

您还可以在“配置变量”部分下的heroku项目设置中添加键值。

希望它能正常工作!