UnhandledPromiseRejectionWarning 使用 sendgrid

问题描述

我已经被困了很长时间了,现在我收到了这个错误,上面写着 UnhandledPromiseRejectionWarning 这不是我在表单控制器中捕获错误的情况

npm 版本

"@sendgrid/mail": "^6.4.0"

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

(node:1504) UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这个错误要么是因为在没有 catch 块的情况下抛出了异步函数,要么是因为拒绝了一个没有用 .catch() 处理过的承诺。要在未处理的承诺拒绝时终止节点进程,请使用 CLI 标志 --unhandled-rejections=strict(请参阅 https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode)。 (拒绝编号: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,message } = req.body;
        // console.log(req.body);
    
        let maillist = [authorEmail,process.env.EMAIL_TO];
    
        const emailData = {
            to: maillist,subject: `Someone messaged you from ${process.env.APP_NAME}`,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 express = require('express');
const router = express.Router();
const { contactForm,contactAssignmentAuthorForm } = require('../controllers/form');

// validators
const { runValidation } = require('../validators');
const { contactFormValidator } = require('../validators/form');

router.post('/contact',contactFormValidator,runValidation,contactForm);
router.post('/contact-assignment-author',contactAssignmentAuthorForm);

module.exports = router;

表单验证器

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.then 方法,如下所示

    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您需要验证您的发件人才能完成此操作