Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript NodeEmailer和HTML模板-循环遍历数组中的项_Javascript_Html_Node.js_Nodemailer - Fatal编程技术网

Javascript NodeEmailer和HTML模板-循环遍历数组中的项

Javascript NodeEmailer和HTML模板-循环遍历数组中的项,javascript,html,node.js,nodemailer,Javascript,Html,Node.js,Nodemailer,我已经开始使用Nodemailer,并且我能够发送电子邮件。我已经决定使用HTML作为一种格式,并包括CSS的引导。我所有的模板变量都得到了正确的插值,但我需要循环一个数组并显示这些项。我目前无法做到这一点,需要一些帮助 router.post('/', auth.isAuthenticated, async (req, res) => { try { // Add request to new object - to save let reque

我已经开始使用Nodemailer,并且我能够发送电子邮件。我已经决定使用HTML作为一种格式,并包括CSS的引导。我所有的模板变量都得到了正确的插值,但我需要循环一个数组并显示这些项。我目前无法做到这一点,需要一些帮助

router.post('/', auth.isAuthenticated, async (req, res) => {
    try {

        // Add request to new object - to save
        let request = new Request(req.body);

        // Save request
        let savedRequest = await request.save();

        // Get request ID and save to associated project
        let project = await Project.findByIdAndUpdate(
            request.project,
            {
                $push: { requests: savedRequest._id }
            },
            { new: true }
        );

        // If notifyPM is true, send request to project manager
        if (req.body.notifyPM) {


            let mailOptions = {
                from: process.env.NODEMAILER_EMAIL,
                to: savedRequest.projectManager.email,
                subject: `PROJECT REQUEST FOR -- ${project.projectTitle} -- FROM -- ${savedRequest.userName}`,
                html: `
                <!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <title>Request</title>
</head>

<body>
  <script>
    ${savedRequest.requestItems}.forEach(myFunction);

function myFunction(item, index) {
  document.getElementById("requestContainer").innerHTML += index + ":" + item + "<br>";
}
  </script>
  <div class="container mt-3">
    <div class="row">
      <div class="col-sm">
        <div class="card">
          <div class="card-header bg-light text-dark">
            <h3><strong>Project: </strong>${project.projectTitle}</h3>
            <h4><strong>From: </strong>${savedRequest.userName}</h4>
          </div>
          <div class="card-body border border-light">
            <div class="row">
              <div class="col-sm">
                <table class="table">
                  <thead>
                    <th>Department</th>
                    <th>Job Type</th>
                    <th>Episode</th>
                  </thead>
                  <tbody>
                    <tr>
                      <td>${savedRequest.department}</td>
                      <td>${savedRequest.jobType}</td>
                      <td>${savedRequest.episode}</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
            <div class="row">
              <div class="col-sm">
                <h5>Request Items</h5>
                <div id="requestContainer"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>

</html>
                            `
            };

            transporter.sendMail(mailOptions, function(error, info) {
                if (error) {
                    console.log(error);
                } else {
                    console.log('Email sent: ' + info.response);
                }
            });
        }

        res.status(200).json({
            message: 'Request saved successfully',
            request: savedRequest
        });
    } catch (error) {
        res.status(500).json({
            message: 'Error saving request'
        });
    }
});

router.post('/',auth.isAuthenticated,async(req,res)=>{
试一试{
//向新对象添加请求-保存
let请求=新请求(请求正文);
//保存请求
让savedRequest=等待请求。save();
//获取请求ID并保存到关联项目
让project=wait project.findByIdAndUpdate(
请求项目,
{
$push:{请求:savedRequest.\u id}
},
{新:正确}
);
//如果notifyPM为true,则向项目经理发送请求
if(请求正文notifyPM){
让邮件选项={
发件人:process.env.nodeEmailer\u电子邮件,
发送至:savedRequest.projectManager.email,
主题:`PROJECT请求--${PROJECT.projectTitle}--FROM--${savedRequest.userName}`,
html:`
要求
${savedRequest.requestItems}.forEach(myFunction);
函数myFunction(项目、索引){
document.getElementById(“requestContainer”).innerHTML+=index+“:“+item+”
”; } 项目:${Project.projectTitle} 发件人:${savedRequest.userName} 部门 工作类型 插曲 ${savedRequest.department} ${savedRequest.jobType} ${savedRequest.eposit} 请求项目 ` }; transporter.sendMail(邮件选项,函数(错误,信息){ 如果(错误){ console.log(错误); }否则{ console.log('发送的电子邮件:'+信息响应); } }); } res.status(200).json({ 消息:“请求已成功保存”, 请求:savedRequest }); }捕获(错误){ res.status(500).json({ 消息:“保存请求时出错” }); } });
这是我的EJS呈现(HTML省略)


决定使用EJS模板。使用EJS绑定创建一个普通HTML页面,然后将HTML页面作为数据与变量对象一起呈现,然后发送。这使我能够循环浏览项目并创建一个好看的电子邮件页面。
// Render EJS
            const data = await ejs.renderFile(
                __dirname + '/workOrderEmailTemplate.ejs',
                {
                    user: wo.user,
                    finalDuration: wo.finalDuration,
                    title: wo.projectTitle,
                    showCode: wo.showCode,
                    episode: wo.episode,
                    woNumber: wo.workOrderNumber,
                    location: wo.location,
                    services: wo.services,
                    clientPresent: wo.clientPresent,
                    woType: wo.workOrderType,
                    notes: wo.notes
                }
            );

            const mailOptions = {
                from: process.env.NODEMAILER_EMAIL,
                to: wo.projectManagerEmail,
                subject: `WORK ORDER for -- ${wo.projectTitle} -- from -- ${wo.user}`,
                html: data
            };

            transporter.sendMail(mailOptions, function(err, info) {
                if (err) {
                    console.log('Error in SendMail function', err);
                } else {
                    console.log('Message sent: ' + info.response);
                }
            });