Node.js中使用Resend库时new运算符报错的解决方法
解决Resend库报错TypeError: resend is not a constructor的问题
核心错误原因
Resend库的CommonJS导入方式并非默认导出构造函数,你直接require("resend")得到的是包含Resend构造函数的对象,而非构造函数本身,所以无法用new resend()实例化。
修复步骤及代码修改
1. 修正工具类sendMail的导入与实例化
修改导入语句,解构出Resend构造函数,同时修复函数内未定义的text参数问题:
const { Resend } = require("resend"); const instanceResend = new Resend(process.env.KEY_RESEND); const sendMail = async (from, to, subject, html, text = "") => { try { const data = await instanceResend.emails.send({ from: from, to: to, subject: subject, html: html, text: text, headers: { "X-Entity-Ref-ID": process.env.KEY_RESEND, }, tags: [ { name: "category", value: "reset_password", }, ], }); console.log("Email data: ", data); return data; } catch (error) { console.error(error); throw error; } }; module.exports = sendMail;
2. 修正控制器中的调用逻辑
sendMail是异步函数,无需传入回调,改用try/catch捕获异常:
const sendMail = require("../utils/sendMail"); forgotPassword: async (req, res) => { const { email } = req.body; try { const user = await userModel.findOne({ email }); if (!email || !user) return res .status(400) .json({ message: "邮箱未找到或无效", success: false }); await sendMail( "from@gmail.com", email, "重置密码通知", "<p>请点击链接完成密码重置</p>", "请点击链接完成密码重置" ); return res.status(200).json({ message: "重置密码邮件已成功发送", success: true, }); } catch (error) { res.status(400).json({ message: "发送重置密码邮件失败,请重试", error: error.message, success: false, }); } },
额外注意事项
- 确保
process.env.KEY_RESEND已正确配置你的Resend API密钥 - 发送邮件的
from地址需是在Resend控制台验证过的域名或邮箱 - 异步函数内抛出错误而非返回错误,能让上层
try/catch更准确捕获异常
内容的提问来源于stack exchange,提问作者Begginer
相关产品推荐
相关产品推荐

