在方法Node.js Express.js之间传递变量

时间:2019-12-05 12:18:43

标签: node.js express

我是Node.js的新手,我试图将用户名参数从app.post()传递给readHtml(),但未定义,我尝试在函数之前声明变量,然后分配里面的值,那么我收到的电子邮件将被发送而不会被替换。

app.post('/sendmail', (req, res) => {
    console.log("mail request came");
    var userName1 = req.body.userInfo.userName;

    sendMail(userMail1, info => {
        console.log(`The mail has beed sent`);
        res.send(info);
    });

}); 

readHTMLFile(__dirname + '/mail.html', function(err, html) {
    var template = handlebars.compile(html);
    var replacements = {
         userName: userName1,
    };
    htmlToSend = template(replacements);
});


async function sendMail(user, callback) {
    let transporter = nodeMailer.createTransport({
        host: '',
        port: 465,
        secure: true,
        auth: {
            user: config.email,
            pass: config.password
        }
    });

    let mailOptions = {
        from: config.email,
        to: user,
        subject: 'Reservation',
        html:htmlToSend,
        attachments: [
    {
      filename: 'logo-01.png',
      path: __dirname + '/img/rsz_1logo-01.png',
      cid: '' 
    }]
    }

    let info = await transporter.sendMail(mailOptions);

    callback(info);
}

1 个答案:

答案 0 :(得分:0)

您对readHTMLFile文件的回调(在启动时仅执行一次)应仅将模板编译为函数。

var template;
readHTMLFile(__dirname + '/mail.html', function(err, html) {
    template = handlebars.compile(html);
});

替换应该发生在针对每个请求执行的sendMail函数中(您对用户对象有引用)。

let mailOptions = {
    from: config.email,
    to: user,
    subject: 'Reservation',
    html: template({userName: user.name}), // <----
    attachments: [
{
  filename: 'logo-01.png',
  path: __dirname + '/img/rsz_1logo-01.png',
  cid: '' 
}]
}
相关问题