简体   繁体   中英

passing variables between methods Node.js Express.js

I'm new to Node.js, and I'm trying to pass the user name parameter from app.post() to readHtml(), but it's not defined, I tried declaring the variable before the function, and assign the value inside it, then the email I'm receiving sent without replacements.

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);
}

Your callback to readHTMLFile file (executed only once at startup) should only compile the template to a function.

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

The replacement should happen in your sendMail function executed for each request (where you have a reference to the user object).

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: '' 
}]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM