我试图在我的应用程序中实现身份验证。但是,应用程序在注册用户时抛出无法设置标头错误。我无法理解为什么通过错误处理函数“wrapAsync”会抛出此错误。
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:387:5)
at ServerResponse.setHeader (node:_http_outgoing:603:11)
at ServerResponse.header (/Users/alisha/Desktop/Oshi/node_modules/express/lib/response.js:794:10)
at ServerResponse.send (/Users/alisha/Desktop/Oshi/node_modules/express/lib/response.js:174:12)
at done (/Users/alisha/Desktop/Oshi/node_modules/express/lib/response.js:1035:10)
at /Users/alisha/Desktop/Oshi/node_modules/ejs-mate/lib/index.js:356:7
at tryHandleCache (/Users/alisha/Desktop/Oshi/node_modules/ejs/lib/ejs.js:280:5)
at Object.exports.renderFile (/Users/alisha/Desktop/Oshi/node_modules/ejs/lib/ejs.js:491:10)
at View.renderFile [as engine] (/Users/alisha/Desktop/Oshi/node_modules/ejs-mate/lib/index.js:298:7)
at View.render (/Users/alisha/Desktop/Oshi/node_modules/express/lib/view.js:135:8)
以下是我的代码块:
1. /注册路由:
router.post('/register', wrapAsync(async(req,res)=>{
const {username, email, nearestLocation, phoneNum, password, RePassword}= req.body;
if(password !== RePassword) {
req.flash('error', 'Please retype same password for confirmation')
return res.redirect('/firm/register')
}
const hashpw= await bcrypt.hash(password, 12);
const registerBusiness= new Businesses({
username: username, email: email, location: nearestLocation, phoneNum: phoneNum, password: hashpw})
await registerBusiness.save();
req.session.currentAccount= registerBusiness.id;
req.session.currentAccountName = registerBusiness.username;
req.flash('success', 'Successfully registered your Business account')
return res.redirect('/home')
}))
2. wrapAsync模块:
module.exports = (fn)=>{
return ((req,res,next)=>{
fn(req,res,next).catch(next)
})
}
有人能给我解释一下这个错误吗?
我希望此代码块为请求发送一个响应。但是,似乎并非如此,而且我也无法确定第二个响应是如何发送的。请帮助我查找答案...
1条答案
按热度按时间dgsult0t1#
从我这边来说,这是一个非常简单的错误。我现在弄清楚了这个问题。router.get和router.post route都在发送对同一个/register请求的响应。