繁体   English   中英

NextJs + Nodemailer + Fetch。 如何接收回复

[英]NextJs + Nodemailer + Fetch. How to receive a response

我正在使用 Next.js、nodemailer 和 fetch 构建一个简单的联系表单。 当表单工作并且目标 email 帐户从前端表单接收 email 时,联系人提交在网络中pending状态。 大约一分钟后,我收到 Next.js 错误读取Unhandled Runtime Error TypeError: Failed to fetch 我觉得这与我使用 Fetch 的方式有关。 我已经习惯了 Axios,并以此为契机让 Fetch 变得更好。 但是我引用了 MDN 的 Fetch页面。

表单.js

 import { useState } from 'react'; const Form = () => { const [name, setName] = useState('') const [email, setEmail] = useState('') const [message, setMessage] = useState('') const [submitted, setSubmitted] = useState(false) const handleSubmit = (e) => { e.preventDefault(); let data = { name, email, message } fetch('/api/contact', { method: 'POST', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json' }, body: JSON.stringify(data) }).then((response) => { /// NOT RECEIVING CONSOLE LOG OR RESPONSE STATUS BELOW console.log('response recieved') if (response.status === 200) { console.log('response succeeded') setSubmitted(true) setName('') setEmail('') setBody('') } }).then(data => { console.log(data) }).then((error) => { console.error(error) }) } return ( <div > < form > < formGroup > < label htmlFor='name'>Name</label> < input type='text' onChange={(e)=>{setName(e.target.value)}} name='name' /> </formGroup> < formGroup > < label htmlFor='email'>Email</label> < input type='text' onChange={(e)=>{setEmail(e.target.value)}} name='email' /> </formGroup> < formGroup > < label htmlFor='message'>Message</label> < input type='text' onChange={(e)=>{setMessage(e.target.value)}} name='message' /> </formGroup> < input type='submit' onClick={(e)=>{handleSubmit(e)}}/> </form > </div> ) } export default Form;

上面的获取引用了下面的联系表格,该表格位于标准 Next.js 项目附带的api文件夹中。 对此进行了几次重构以查看是否有任何区别,包括 async/await。

联系.js

 export default function (req, res) { require('dotenv').config(); let nodemailer = require('nodemailer') const transporter = nodemailer.createTransport({ port: 465, host: "smtp.gmail.com", auth: { user: 'samplenodemailer@email.com', pass: process.env.password, }, secure: true, }) const mailData = { from: 'samplenodemailer@email.com', to: 'targetinbox@email.com', subject: `Test Quote Submission From: ${req.body.name}`, text: req.body.message + " | Sent from: " + req.body.email, html: `<div>${req.body.message}</div><p>Sent from: ${req.body.email}</p>` } transporter.sendMail(mailData, function (err, info) { if(err) {console.log(err)} else {console.log(info)} }) res.status(200) }

我不确定我要去哪里错了。 我觉得这与我在Form.js中处理 Fetch 的方式有关。 任何帮助或建议将不胜感激。

编辑这里是一些相关的日志

终端: API resolved without sending a response for /api/contact, this may result in stalled requests.

在您的 API 路由中, res.status(200)单独不会发送响应 - 您需要调用end()

export default function (req, res) {
    //...
    res.status(200).end()
}

暂无
暂无

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

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