我正在编写一个Node.js Web应用程序,它使用Express作为框架,Nunjucks作为模板引擎。
该应用程序的一部分是将表单数据作为电子邮件发送。在此过程中编译带有表单数据的Nunjucks模板,然后将其发送到电子邮件服务器。
表单数据是一个JSON对象(req.body
),但由于某些奇怪的原因,我需要像这样提交表单数据:
const renderer = nunjucks.configure('/path/to/template');
renderer.render('template.html', JSON.parse(JSON.stringify(req.body)));
简单地写renderer.render('template.html', req.body);
不起作用,它会引发错误:
TypeError: ctx.hasOwnProperty is not a function
at Obj.extend.init (D:\Projects\vcs.vitra.com\node_modules\nunjucks\src\environment.js:338:20)
at new new_cls (D:\Projects\vcs.vitra.com\node_modules\nunjucks\src\object.js:46:28)
at Obj.extend.render (D:\Projects\vcs.vitra.com\node_modules\nunjucks\src\environment.js:473:23)
at D:\Projects\vcs.vitra.com\node_modules\nunjucks\src\environment.js:311:35
at createTemplate (D:\Projects\vcs.vitra.com\node_modules\nunjucks\src\environment.js:234:25)
at handle (D:\Projects\vcs.vitra.com\node_modules\nunjucks\src\environment.js:249:25)
at D:\Projects\vcs.vitra.com\node_modules\nunjucks\src\environment.js:263:21
at next (D:\Projects\vcs.vitra.com\node_modules\nunjucks\src\lib.js:207:13)
at Object.exports.asyncIter (D:\Projects\vcs.vitra.com\node_modules\nunjucks\src\lib.js:214:5)
at Obj.extend.getTemplate (D:\Projects\vcs.vitra.com\node_modules\nunjucks\src\environment.js:242:17)
有人知道为什么我需要在Nunjucks工作之前对表单数据进行字符串化和解析吗?似乎没有任何意义吗?
修改
以下是整个功能,以便更好地解释:
功能
function sender(data, callback) {
const config = require('./config'),
renderer = nunjucks.configure(path.join(__dirname, 'views', 'mail-templates')),
transporter = nodemailer.createTransport((smtpTransport(config.smtp)));
transporter.sendMail({
from: `${data.name} <${data.email}>`,
replyTo: data.email,
to: config.email.receiver,
subject: config.email.subject,
html: renderer.render(`${data.origin}.html`, JSON.parse(JSON.stringify(data))),
}, callback);
}
函数调用
sender(req.body, (message, err) => {
res.json({ message: message, errors: err });
});
req.body aka data
{ contacttype: 'E-Mail',
software: '',
text: 'Test',
email: '',
name: '',
origin: 'contact' }
答案 0 :(得分:2)
尝试将更改代码改为
function sender(data, callback) {
const config = require('./config'),
renderer = nunjucks.configure(path.join(__dirname, 'views', 'mail-templates')),
transporter = nodemailer.createTransport((smtpTransport(config.smtp)));
renderer.render(`${data.origin}.html`, data, function(err, html){
if (err)
return callback(err);
transporter.sendMail({
from: `${data.name} <${data.email}>`,
replyTo: data.email,
to: config.email.receiver,
subject: config.email.subject,
html: html
}, callback
);
});
}
要创建对象的复制/混合,请使用Object.assign
let copy = Object.assign({}, src1, src2);