[英]Passport.js -- how to use render email asynchronously
我正在使用 Sequelize/MariaDB 和 Passport.js 運行 Express 以進行用戶身份驗證。
我在注冊部分(有效)但我似乎無法呈現和返回激活電子郵件,要求他們確認他們的電子郵件。
passport.js
(包含身份驗證策略)
passport.use('user-signup-email', new LocalStrategy({
//Process/validate input, check database for existing emails, create user, add to database...
...
if (newUser) {
var token = jwt.sign( { data: newUser.id }, newUser.login_pass + "-" + newUser.account_created);
var URLdata = {
id: newUser.id,
expiration_time: Date.now() + 86400000, //24 hours
url: token,
email_info: mail.createActivationEmail(req.app, newUser.login_key, newUser.user_alias, token)
};
console.log("info: " + URLdata.email_info);
...
//Store dynamic URL and email contents (in case of resending) in database with expiration time
//And then send the email that was just rendered
}
mail.js
exports.createActivationEmail = (app, recipientAddress, userName, url) => {
app.render('emails/activation_email', {
layout: false,
page_title: 'Please confirm your account!',
dynamic_url: url
}, function(err, rendered) {
if (err) {
console.log("Q [" + err + "]");
}
console.log("R " + rendered.toString());
return {
from: adminEmailAddress,
to: recipientAddress,
cc: false,
bcc: false,
subject: 'Welcome to example.com ' + userName + '!',
html: rendered.toString(),
text: "TO DO"
};
});
};
passport.js
的最后一個console.log
顯示“信息:未定義”。 但是如果我在返回之前在mail.js
模塊中打印輸出,那mail.js
。
我猜這是一個異步問題? 我將如何修復它?
在這種情況下,我對 promise 和 async-await 塊仍然有點不清楚。
在此先感謝您提供的任何幫助!
你誤解了回調函數。 回調是(應該,當你編寫它們時)異步: https : //nemethgergely.com/async-function-best-practices/ 如何為 Node.js 編寫異步函數
我更改了您的createActivationEmail
函數。 最后一個參數現在是一個回調,當你的代碼app.redner
完成時它會被調用。
passport.use('user-signup-email', new LocalStrategy({ //Process/validate input, check database for existing emails, create user, add to database... // ... if(newUser) { var token = jwt.sign({ data: newUser.id }, newUser.login_pass + "-" + newUser.account_created); mail.createActivationEmail(req.app, newUser.login_key, newUser.user_alias, token, (err, email_info) => { var URLdata = { id: newUser.id, expiration_time: Date.now() + 86400000, //24 hours url: token, email_info }; console.log("info: " + URLdata.email_info); //... //Store dynamic URL and email contents (in case of resending) in database with expiration time //And then send the email that was just rendered }); } }));
exports.createActivationEmail = (app, recipientAddress, userName, url, done) => { app.render('emails/activation_email', { layout: false, page_title: 'Please confirm your account!', dynamic_url: url }, function(err, rendered) { if (err) { console.log("Q [" + err + "]"); cb(err); return; } console.log("R " + rendered.toString()); done(null, { from: adminEmailAddress, to: recipientAddress, cc: false, bcc: false, subject: 'Welcome to example.com ' + userName + '!', html: rendered.toString(), text: "TO DO" }); }); };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.