简体   繁体   English

如何从 Nodemailer 发送响应

[英]How to send response from Nodemailer

I have an app written with React as the frontend, and Express as the backend.我有一个用 React 作为前端,用 Express 作为后端编写的应用程序。 I'm using Nodemailer to email out the results of a form.我正在使用 Nodemailer 以 email 的形式输出结果。 It hits the backend and sends out just fine, but I'm looking for the proper way to send a response back to the front end so that I can alert the user if there's an error, or redirect to a success page if it goes through fine.它到达后端并发送出去就好了,但我正在寻找将响应发送回前端的正确方法,以便我可以在出现错误时提醒用户,或者在它通过时重定向到成功页面美好的。 I've tried both using a callback function and omitting it in my transporter.sendMail() code and neither have worked.我尝试过使用回调 function 并在我的 transporter.sendMail() 代码中省略它,但都没有用。 I don't really know what I'm doing, and could use some help.我真的不知道我在做什么,需要一些帮助。

Transporter Code (Wrapped inside my sendMail function)传输代码(包装在我的 sendMail 函数中)

transporter.sendMail(mailOptions, (err, info) => {
            if (err) {
                console.log(err)
                res.sendStatus(500)
            } else {
                console.log(info)
                res.sendStatus(201)
            }
        })

Server Code服务器代码

app.post('/sendApplication', cpUpload, async (req, res) => {
    return sendMail(req.files['essay'][0], req.files['recLetter1'][0], req.files['recLetter2'][0], req.body)
})

Form Submit Code表单提交代码

handleSubmit = async (e) => {
    e.preventDefault()
    let formData = new FormData()
    for (let i in this.state.formValues) {
        formData.append(i, this.state.formValues[i])
    }
    formData.append('essay', document.getElementById('essay').files[0])
    formData.append('recLetter1', document.getElementById('recLetter1').files[0])
    formData.append('recLetter2', document.getElementById('recLetter2').files[0])
    await fetch('/sendApplication', {
        method: 'POST',
        body: formData
    }).then((res) => {
        if (res.ok) {
            window.localStorage.removeItem('applicationData')
            this.props.history.push('/success')
        } else {
            alert('Error Message')
        }
    })
}

First, you need to add (req,res,next) in you controller function to use res function.首先,您需要在 controller function 中添加(req,res,next)以使用 res function。

After this, you will be able to return res to the client.在此之后,您将能够将 res 返回给客户端。

Try this:尝试这个:

const sendMail = (res,req,next) => {
     
      /// 
transporter.sendMail(mailOptions, (err, info) => {
            if (err) {
                console.log(err)
                res.status(500).send({err : err})
            } else {
                console.log(info)
                res.status(200).send({success : info})
            }
        })
      ///
}

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

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