[英]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.