未处理的承诺拒绝使用 sendgrid 和 nodejs

mix*_*ixx 1 javascript node.js sendgrid

我是这些语言的新手,我正在从事一个项目,该项目提供用户数据库管理和每个用户的功能,通过按钮,向他们发送带有代码的电子邮件。我正在使用nodejsexpressjs(数据库)和sendgrid,这些是它们的版本(我认为它们是最后一个):

"@sendgrid/mail": "^6.2.1", "sendgrid-rest": "^2.4.0", "express": "^4.16.2", node v8.9.4

我正在使用Windows 10,并通过官方 sengrid 指南获得了以下代码:

exports.sendMail = function(req,res){

var name = req.params.nome;
var email = req.params.email;
var code = req.params.code;

const  sgMail = require('@sendgrid/mail');
sgMail.setApiKey('api_key');
const  msg = {
  to: email,
  from: 'a@b.com',
  subject: 'event',
  text: 'Dear '+name+',\n'+'this is your code: \n',
  html: '<br><strong>'+code+'</strong><br>',
};
sgMail.send(msg).then(() => {
    res.redirect('/users');
}).catch((error) => {
    console.log('error', error);
});

}
Run Code Online (Sandbox Code Playgroud)

我尝试通过 Windows 设置创建环境变量,但没有用。我找到了另一个建议创建.env文件并导出包含 sendgrid api_key 的变量的解决方案:

export SENDGRID_API_KEY = 'SG.xxx...'
Run Code Online (Sandbox Code Playgroud)

但暂时它似乎不起作用,而是我收到了这些消息,并且没有发送电子邮件。我检查了 api_key 的正确性,是 SG.XXXXX... 开头的那个,所以我认为是正确的。以下是消息:

(node:9688) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Provide at least one of to, cc or bcc
(node:9688) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Run Code Online (Sandbox Code Playgroud)

它们是简单的警告,但我担心它们会影响操作。

另一个问题:我在一些帖子中看到,在项目目录中的一个文件中使用了api_key(我认为他们说的是公共目录(/project/public)),我将该文件放在我项目的主目录中( / 项目),存在安全问题,因为它可以从外部看到,我所做的是否安全?我是否必须将其移动到其他目录?

欢迎提供任何帮助,我认为在 Web 应用程序中使用 sendgrid 服务会容易得多。如果通过 sendgrid 有更快的方法,欢迎使用。

编辑:多亏了我设法得到部分解决方案的答案,修改了上面的代码,我没有收到任何错误,但似乎没有向邮箱发送任何电子邮件。一些帮助?

Rah*_*rma 6

试试这个,你没有处理错误情况。Error: Provide at least one of to, cc or bcc可能是电子邮件为空/未定义。

sgMail.send(msg).then(() => {
    res.redirect('/users');
}).catch((error) => {
    console.log('error', error);
});
Run Code Online (Sandbox Code Playgroud)