javascript - 使用 nodemailer 页面发送邮件后开始加载而不实际更改元素/页面
问题描述
我在反应组件中有这个基本形式:
<form method="POST" action="/sendcontact" encType="multipart/form-data" className="contact-form">
<label>* Your name</label>
<input
type="text"
name="username"
placeholder="Your name"
required
/>
<label>* E-mail</label>
<input
type="email"
name="email"
placeholder="Your e-mail"
required
/>
<label>* Message</label>
<textarea
name="message"
placeholder="Your message here..."
required
/>
<button type="submit" className="submit-btn">Submit</button>
</form>
index.js(节点)
app.post('/sendcontact',(req,res) => {
upload(req,res,function(err){
if(err){
console.log(err)
return res.end("Something went wrong!");
}else{
let mailOptions = {
from: req.body.email,
to: 'mymail@gmail.com',
subject: `New message from ${req.body.email}`,
text: req.body.message
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
}
})
});
邮件成功发送,但提交表单后,页面基本上永远加载,除非我手动停止它。通过加载我的意思是在网页标签上,在页面名称旁边: https ://imgur.com/a/jKJZkYW
我真的不知道是什么原因造成的,但我想修复它,这样用户就不会因为页面开始加载而认为实际发生了什么。
我注意到如果在 React 组件中我使用状态来存储表单值并通过 axios 将它们发送到节点,它的行为就不会像这样,但我不能这样做,因为我必须发送一个input[type="file"] 也是,我还没有弄清楚如何用 axios 做到这一点。
解决方案
每次我们向服务器发出请求时,浏览器都会等待响应(如 Molda 的评论中所述)。
基本上,在提交表单后,发送一个http.post
to '/sendcontact'
,在控制器内部不会调用任何错误来输入if(err)
. 这意味着您的服务器不会以res.end(), res.send(), res.json() or res.redirect()
返回用户浏览器的形式返回任何响应。
一个好的做法是将其重定向到成功页面,在成功的情况下调用res.redirect('/<wanted path'>)
内部,或者在关闭函数transporter.sendMail
后简单地重定向到默认页面。trasporter.sendMail
推荐阅读
- javascript - Kendo UI 下拉列表已选中
- java - 使用 2d 数组和 for 循环的 Mailman 邮箱问题
- java - Spring Data Rest JPA rest service with hibernate:控制延迟加载
- javascript - 如何从 javascript 函数内部调用 jquery buttonclick 函数
- ant - 带有空输入字符串的 apache Ant 基本名称问题
- asp.net-mvc - Azure 应用服务上的瞬态无限登录循环 - 使用 Azure AD 进行 OpenIDConnect 身份验证
- php - 如何从字符串中添加数字
- html - Bootstrap 4 - Ubuntu Chrome 和 Firefox 中不同的渲染字体大小
- python - 使用opencv和python从具有可变帧速率的IP摄像机录制视频
- android - 如何使用 Mockito 的 doAnswer 测试 void 方法