创建用户ERR_HTTP_HEADERS_SENT后,使用next.js API发送电子邮件



我目前正在使用next.js API创建用户,但是,我现在想使用sendgrid发送电子邮件。

我有这个设置,然而,我得到以下

event - compiled successfully in 661 ms (254 modules)
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (internal/errors.js:322:7)
at ServerResponse.setHeader (_http_outgoing.js:561:11)
at DevServer.renderError (/Users/ellisbrookes/Documents/Ellis-Developement/node_modules/next/dist/server/next-server.js:1628:17)
at DevServer.run (/Users/ellisbrookes/Documents/Ellis-Developement/node_modules/next/dist/server/dev/next-dev-server.js:431:35)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async DevServer.handleRequest (/Users/ellisbrookes/Documents/Ellis-Developement/node_modules/next/dist/server/next-server.js:305:20) {
code: 'ERR_HTTP_HEADERS_SENT'
}
error - Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
error - uncaughtException: Error [ERR_STREAM_WRITE_AFTER_END]: write after end

正在创建用户并发送电子邮件,但是,我不确定为什么会出现此错误。

以下是我在形式上对onSubmitAPI调用的了解

const res = await fetch('/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})

这是我在api/auth/register文件中的内容

import connectDB from '../../../lib/mongodb'
import bcrypt from 'bcrypt'
import User from '../../../models/user'
const mail = require('@sendgrid/mail');
mail.setApiKey(process.env.SENDGRID_API_KEY);
const handler = async (req, res) => {
// check if user exists in the database already
const emailExists = await User.findOne({ email: req.body.email })
if (emailExists) return res.status(400).send("Email already exists")
// hash password
const salt = await bcrypt.genSalt(10)
const hash = await bcrypt.hash(req.body.password, salt)
var user = new User({
firstname: req.body.firstname,
lastname: req.body.lastname,
username: req.body.username,
email: req.body.email,
password: hash
})
try {
user = await user.save();
res.send({ user: user._id })
} catch {
res.status(400).send(err)
}
// nodemailer
const message = `
First Name: ${req.body.firstname}rn
Last Name: ${req.body.lastname}rn
Username: ${req.body.username}rn
Email: ${req.body.email}
`;
const data = {
to: `${req.body.email}`,
from: 'Ellis Development <hello@ebrookes.dev>',
subject: `Welcome ${req.body.firstname} ${req.body.lastname} to Ellis Development`,
text: message,
html: message.replace(/rn/g, '<br />')
};
await mail.send(data);
res.status(200).json({ status: 'OK' });
}
export default connectDB(handler)

如前所述,正在创建用户并发送电子邮件,但不确定我为什么会收到ERR_HEADERS错误。

在try-catch块中,在不停止函数的情况下发送响应res.send({ user: user._id })。该功能继续执行,您尝试发送另一个响应res.status(200).json({ status: 'OK' });

我建议将try-catch块更改为:

try {
user = await user.save();
} catch {
return res.status(400).send(err)
}

如果出现错误(返回语句(,这将停止执行,但如果user.save()成功完成,则将继续执行。最后,它将在最后返回200{status: OK}响应。

最新更新