Node.js 使用sendgrid未处理PromisejectionWarning

Node.js 使用sendgrid未处理PromisejectionWarning,node.js,express,postman,sendgrid,Node.js,Express,Postman,Sendgrid,我被困了很长一段时间,现在我得到了这个错误,上面写着UnhandledPromisejectionWarning,这不是我在表单控制器中捕捉到的错误 npm版本 @sendgrid/mail:“^6.4.0” 当我尝试使用邮递员正文发送电子邮件时: (节点:1504)未处理的PromisejectionWarning:未处理的承诺拒绝。此错误源于在没有catch块的异步函数中抛出,或者拒绝未使用.catch()处理的承诺。要在未处理的承诺拒绝时终止节点进程,请使用CLI标志--unhandled

我被困了很长一段时间,现在我得到了这个错误,上面写着UnhandledPromisejectionWarning,这不是我在表单控制器中捕捉到的错误

npm版本

@sendgrid/mail:“^6.4.0”

当我尝试使用邮递员正文发送电子邮件时:

(节点:1504)未处理的PromisejectionWarning:未处理的承诺拒绝。此错误源于在没有catch块的异步函数中抛出,或者拒绝未使用.catch()处理的承诺。要在未处理的承诺拒绝时终止节点进程,请使用CLI标志
--unhandled rejections=strict
(请参阅)。(拒绝id:2)

这个对象是我从捕捉错误中得到的

code: 403,
  response: {
    headers: {
      server: 'nginx',
      date: 'Fri, 16 Apr 2021 04:16:35 GMT',
      'content-type': 'application/json',
      'content-length': '281',
      connection: 'close',
      'access-control-allow-origin': 'https://sendgrid.api-docs.io',
      'access-control-allow-methods': 'POST',
      'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-of, x-sg-elas-acl',
      'access-control-max-age': '600',
      'x-no-cors-reason': 'https://sendgrid.com/docs/Classroom/Basics/API/cors.html',
      'strict-transport-security': 'max-age=600; includeSubDomains'
    },
    body: { errors: [Array] }
  }
}

 {
        "name":"fares",
        "email":"essayehfares@gmail.com",
        "message":"This is test This is testThis is testThis is testThis is testThis is testThis is testThis is testThis is testThis is testThis is testThis is testThis is testThis is testThis is testThis is test This is test" 
}
电子邮件表单控制器

const sgMail = require('@sendgrid/mail'); // SENDGRID_API_KEY
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

    exports.contactForm = (req, res) => {
        const { email, name, message } = req.body;
        // console.log(req.body);
    
        const emailData = {
            to: process.env.EMAIL_TO,
            from: email,
            subject: `Contact form - ${process.env.APP_NAME}`,
            text: `Email received from contact from \n Sender name: ${name} \n Sender email: ${email} \n Sender message: ${message}`,
            html: `
                <h4>Email received from contact form:</h4>
                <p>Sender name: ${name}</p>
                <p>Sender email: ${email}</p>
                <p>Sender message: ${message}</p>
                <hr />
                <p>This email may contain sensetive information</p>
            `
        };
    
        sgMail.send(emailData).then(sent => {
            return res.json({
                success: true
            }).catch(error=>{
                console.log('error',error)
            })
        
        });
    };
    
    exports.contactAssignmentAuthorForm = (req, res) => {
        const { authorEmail, email, name, message } = req.body;
        // console.log(req.body);
    
        let maillist = [authorEmail, process.env.EMAIL_TO];
    
        const emailData = {
            to: maillist,
            from: email,
            subject: `Someone messaged you from ${process.env.APP_NAME}`,
            text: `Email received from contact from \n Sender name: ${name} \n Sender email: ${email} \n Sender message: ${message}`,
            html: `
                <h4>Message received from:</h4>
                <p>name: ${name}</p>
                <p>Email: ${email}</p>
                <p>Message: ${message}</p>
                <hr />
                <p>This email may contain sensetive information</p>
         
            `
        };
    
        sgMail.send(emailData).then(sent => {
            return res.json({
                success: true
            }).catch((error) => {
                console.log('error', error);
            });
        });
    };
表单验证程序

const { check } = require('express-validator');

exports.contactFormValidator = [
    check('name')
        .not()
        .isEmpty()
        .withMessage('Name is required'),
    check('email')
        .isEmail()
        .withMessage('Must be valid email address'),
    check('message')
        .not()
        .isEmpty()
        .isLength({ min: 15 })
        .withMessage('Message must be at least 20 characters long')
];
环境文件

NODE_ENV=development
APP_NAME=SUIVISTAGE
PORT=8000
CLIENT_URL=http://localhost:3000
DATABASE_LOCAL='mongodb://localhost:27017/stage'
JWT_SECRET=KDJHF7823RHIU3289FJ932I2G8FG239
SENDGRID_API_KEY=SG.5YsBW3I7Ra2IcLLiJXfc1g.R1XYPG3SyWfyl0G1w0D5hsh5CGvECIvjYSjRcHtisDc
EMAIL_TO=faresessayeh@gmail.com

您在错误的行中使用catch,
res.json
不需要
catch
块。将catch块连接到
sendgrid。然后使用如下方法

    sgMail.send(emailData).then(sent => {
        return res.json({
            success: true
        })
    }).catch(error=>{
       console.log('error',error)
    })

另外,不要在公共场合发布这样的API密钥,它们不需要理解您的代码。

按照本指南sendgrid.com/docs/ui/sending email/sender verification解决了问题。您需要验证您的发件人才能完成此操作。

仍然无法解决同一问题,sendgrid中是否有任何配置我应该关心设置->Api键->我创建了一个,并复制了它,就是说,有两个地方你必须做相同的事情(catch block),你更新了这两个地方吗(即在
contactAssignmentAuthorForm
contactForm
功能中?我只是在经过大量研究后更新了代码,我认为他们更新了身份验证的方式,它需要一些配置[链接]我查看了,似乎首先您必须创建发件人的身份和API密钥,并将特定IP地址的列表添加到列表中才能成功发送电子邮件。您可以使用
error.response.body
记录错误响应正文,以详细查看错误。
    sgMail.send(emailData).then(sent => {
        return res.json({
            success: true
        })
    }).catch(error=>{
       console.log('error',error)
    })