繁体   English   中英

使用 nodemailer 页面发送邮件后开始加载而不实际更改元素/页面

[英]After sending mail with nodemailer page starts loading without actually changing elements/the page

我在反应组件中有这个基本形式:

<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);
                }
            });
        }
    })
});

邮件成功发送,但提交表单后,页面基本上永远加载,除非我手动停止它。 通过加载我的意思是在 web 选项卡上,在页面名称旁边: https://imgur.com/a/jKJZkYW

我真的不知道是什么原因造成的,但我想修复它,这样用户就不会因为页面开始加载而认为实际发生了什么。

我注意到如果在 React 组件中我使用 state 来存储表单值并通过 axios 将它们发送到节点,它不会像这样,但我不能这样做,因为我必须发送input[type="file"] 也是,我还没有弄清楚如何使用 axios 做到这一点。

每次我们向服务器发出请求时,浏览器都会等待响应(如 Molda 的评论中所述)。

基本上,在提交表单后,将http.post发送到'/sendcontact' ,在 controller 中不会调用任何错误来输入if(err) 这意味着您的服务器不会以res.end(), res.send(), res.json() or res.redirect()的形式将任何响应返回给用户的浏览器。

一个好的做法是将其重定向到成功页面,在成功的情况下调用transporter.sendMail内部的res.redirect('/<wanted path'>) ,或者在关闭trasporter.sendMail

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM