尝试使用Sendgrid发送电子邮件后出现网络错误

时间:2018-12-04 12:51:29

标签: javascript node.js express sendgrid

我正在使用MERN堆栈菜单,我想使用Sengrid发送电子邮件。在客户应用程序中,用户将提供标题,正文,主题以及收件人字段中的电子邮件列表,并用逗号分隔,后端使用express来处理传入的HTTP POST请求,然后再将其发送到SendGrid API。这是Express中的代码:

Mailer.js

const sendgrid=require('sendgrid');
const helper=sendgrid.mail;
const keys=require('../config/keys');

class Mailer extends helper.Mail{
    constructor({subject,recipients},content){
        super();
        this.sgApi=sendgrid(keys.sendGridKey);
        this.from_email=new helper.Email('no-reply@emaily.com');
        this.subject=subject;
        this.body=new helper.Content('text/html',content);
        this.recipients=this.formatAddresses(recipients);

        this.addContent(this.body);
        this.addClickTracking();
        this.addRecipients();
    }

    formatAddresses(recipients){
        return recipients.map(({email})=>{
            return new helper.Email(email);
        });
    }

    addClickTracking(){
        const trackingSettings=new helper.TrackingSettings();
        const clickTracking=new helper.ClickTracking(true,true);

        trackingSettings.setClickTracking(clickTracking);
        this.addTrackingSettings(trackingSettings);
    }

    addRecipients(){
        const personalize=new helper.Personalization();
        this.recipients.forEach(recipient=>{
            personalize.addTo(recipient);
        });
        this.addPersonalization(personalize);
    }

    async send(){
        const request=this.sgApi.emptyRequest({
            method:'POST',
            path:'/v3/mail/send',
            body:this.toJSON()
        });
        const response=this.sgApi.API(request);
        return response;
    }

}

module.exports=Mailer;

The route

const mongoose=require('mongoose');
const requireLogin=require('../middlewares/requireLogin');
const requireCredits=require('../middlewares/requireCredits');
const Mailer=require('../services/Mailer');
const surveyTemplate=require('../services/emailTemplates/surveyTemplate');

const Survey=mongoose.model('surveys');

module.exports=app=>{
    app.post('/api/surveys',requireLogin,requireCredits,async(req,res)=>{
        const { title,subject,body,recipients }=req.body;
        const survey=await new Survey({
            title,
            body,
            subject,
            recipients:recipients.split(',').map(email=>({email})),//for every email string got after spliting,we create an object of key string and value of whatever email
            _user:req.user.id,
            dateSent:Date.now()
        });
        const mailer=new Mailer(survey,surveyTemplate(survey));
        mailer.send();
    });
}

当我尝试发送时,在4或5分钟后,出现以下错误 Browser debugger windows

在讲师的计算机上,代码与我的代码完全相同,但我不知道为什么我的代码未按预期运行

0 个答案:

没有答案