我目前正在使用 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}\r\n
Last Name: ${req.body.lastname}\r\n
Username: ${req.body.username}\r\n
Email: ${req.body.email}
`;
const data = {
to: `${req.body.email}`,
from: 'Ellis Development <[email protected]>',
subject: `Welcome ${req.body.firstname} ${req.body.lastname} to Ellis Development`,
text: message,
html: message.replace(/\r\n/g, '<br />')
};
await mail.send(data);
res.status(200).json({ status: 'OK' });
}
export default connectDB(handler)
如前所述,正在創建用戶并正在發送電子郵件,但不確定為什么我會收到ERR_HEADERS錯誤訊息。
uj5u.com熱心網友回復:
在 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} 回應。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/358704.html
