2016-12-07 59 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'});