2016-12-07 21 views
0

我想通过nodemailer发送电子邮件后,使用HTML显示确认消息。我对节点相当陌生,所以我不确定是否缺少明显的东西。Node.js使用回调函数更改HTML代码

app.post("/bye", function(req, res){ 
    // send e-mail 
    var transporter = nodemailer.createTransport({ 
     ... 
    }); 

    var mailOptions = { 
     ... 
    } 

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

     ... (Something here that is going to print a confirmation message to the html code of the page) 
    }); 

    res.end("yes"); 
}); 

感谢

回答

0

节点完全独立于浏览器运行,因此您不能直接在浏览器中从节点修改HTML。您需要从节点向浏览器发送响应,然后在浏览器中处理该响应。 (如果你喜欢使用jQuery后为了简单,但普通的JavaScript请求,或另一个库)它可能工作是这样的......

节点

app.post("/bye", function(req, res){ 
    // send e-mail 
    var transporter = nodemailer.createTransport({ 
    ... 
    }); 

    var mailOptions = { 
     ... 
    } 

    transporter.sendMail(mailOptions, function(error, info){ 
     if(error){ 
      console.log(error) 
      res.end({ 
       success: false, 
       msg: error 
      }); 
     } 

     console.log('Message sent: ' + info.response); 

     res.end({ 
      success: true 
     }); 
    }); 
}); 

然后在客户端的JavaScript ...

$.post('/bye').then(function(response) { 
    if (response.success) { 
     $('#msg').text('Your message was sent'); 
    } else { 
     $('msg').text(response.msg); 
    } 
}).catch(function(err) { 
    $('#msg').text('Could not reach server'); 
}); 
0

res的对象发送回客户端。

你可以用你的留言:

res.send('your message'); 

,我会在最后删除您res.end("yes");。它会在发送完邮件之前发送回复。

因此您的代码将是如下:

app.post("/bye", function(req, res){ 
    // send e-mail 
    var transporter = nodemailer.createTransport({ 
     ... 
    }); 

    var mailOptions = { 
     ... 
    } 

    transporter.sendMail(mailOptions, function(error, info){ 
     if(error){ 
      res.status(500).end('error'); 
      return console.log(error); 
     } 
     console.log('Message sent: ' + info.response); 

     res.status(200).send('your message'); 
    }); 
}); 

Tutorialspoint有明确的一个很好的介绍。也许它可以帮助你。

1

您应该将呼叫转移到res.end()sendMail()回调内部,例如:

app.post("/bye", function (req, res) { 
    // send e-mail 
    var transporter = nodemailer.createTransport({}); 

    var mailOptions = {}; 
    transporter.sendMail(mailOptions, function(error, info){ 
     if (error) { 
      console.log(error); 

      res.status(500).send({ 
       message: 'Unable to send mail' 
      }); 
     } 

     console.log('Message sent: ' + info.response); 

     res.status(200).send({ 
      message: 'Mail sent successfully' 
     }); 
    }); 
}); 

然后你需要处理客户端上的这条消息呈现一个不错的或失败的消息给用户。

0

也许你可以将你的res.end("...")放入你的.sendMail(... function() {而不是之后。

0

,如果你想显示整个HTML页面,你可以发送和HTML文件到浏览器:

res.sendfile('views/test.html', {root: __dirname })

否则,如果你想显示在当前的HTML错误消息你应该发送json数据到客户端,包含消息,消息类型等等,解析客户端中的json并渲染它:

res.send(JSON.stringify({message: 'message' , type: 'success'});