首页 > 解决方案 > 使用 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 做到这一点。

标签: javascriptnode.jsreactjsaxios

解决方案


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

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

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


推荐阅读