我使用nodemailer在用户提交联系表单后发送电子邮件,然后用户将被引导至感谢页面。我现在在cloud9上从事这个项目。这是我的代码:
var express = require("express"),
bodyParse = require("body-parser"),
multer = require("multer"),
nodemailer = require("nodemailer");
var app = express();
app.use(bodyParse.urlencoded({extended: true}));
var smtpTransport = nodemailer.createTransport({
service: "Gmail",
auth: {
type: "OAuth2",
user: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c34343434340c2b212d2520622f2321" rel="noreferrer noopener nofollow">[email protected]</a>",
clientId: "xxxxxx",
clientSecret: "xxxxx",
refreshToken: "xxxxx",
accessToken: "xxxxx"
}
});
app.post("/upload", function(req, res){
var mailOptions = {
from: "xxxx <<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c4bcbcbcbc84a3a9a5ada8eaa7aba9" rel="noreferrer noopener nofollow">[email protected]</a>", // sender address
to: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e79f9f9f9fa7808a868e8bc984888a" rel="noreferrer noopener nofollow">[email protected]</a>", // list of receivers
subject: "xxxx", // Subject line
text: "xxxx",
attachments: [
{ // file on disk as an attachment
filename: 'xxxx.txt',
path: './uploads/' + req.body.filename // stream this file
}
]
};
// send mail with defined transport object
smtpTransport.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message %s sent: %s', info.messageId, info.response);
});
})
电子邮件可以成功发送出去,提交表单后几秒钟就可以看到它,但页面会一直加载,直到显示一些错误(我在下面附上了错误消息)。在此期间,我会再收到 1 到 2 封相同的电子邮件。
<html>
<head>
<meta charset='utf-8'>
<title>Error 502 - Bad Gateway</title>
<link rel="stylesheet" type="text/css"
href="https://cdn.c9.io/errors/style.css" />
<style type="text/css">
.error_content {
background: rgba(255, 255, 255, 0.23);
padding: 10px;
width: 641px;
margin: 25px 0;
display: none;
}
#error-msg {
display: block;
}
</style>
</head>
<body class="errorUnknown light">
<div id="wrapper">
<h1>Error 502 - Bad Gateway</h1>
<div class="error_content" id="error-msg">
<p>Please click <a href="javascript:location.reload(true)">here</a> to try again, if the issue persists please contact <a href="https://c9.io/support">support</a></p>
</div>
<a href="http://status.c9.io">Status Page</a> |
<a href="https://c9.io/support">Support</a> |
<a href="https://c9.io/dashboard.html">Dashboard</a> |
<a href="https://c9.io">Home</a>
</div>
</body>
</html>
QQQQQ:我应该怎么解决这个问题? QQQQQ:这是我代码的问题还是cloud9服务器的问题?
最佳答案
这是因为您从未在 app.post()
处理程序中将响应发送回浏览器。因此,浏览器只是一直等待服务器的回复,但它永远不会——最终超时。这完全是您的代码,与您的云提供商无关。
在您的 app.post()
处理程序中,您需要某种响应内容,例如 res.send(xxx)
来告诉浏览器 post 请求已完成。如果此 POST 来自 ajax 调用,那么您可以将您想要的任何响应发送回客户端 Javascript。如果 POST 请求是浏览器中的表单提交,那么您需要发回一个 HTML 页面,浏览器将加载该页面并向用户显示。
关于node.js - Nodemailer 发送电子邮件后速度非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43460537/