next-connect中的链接中间件出现错误处理程序失败



我有以下两个中间件函数:

function validateEmail(req, res, next) {
console.log('email validation');
if (req.body.email && req.body.email.match(EMAIL_REGEX)) {
console.log('email OK!');
return next(req, res);
} else {
console.log('email wrong');
res.json({ message: 'email invalid'});
}
}
function  validateOriginHeader(req, res, next) {
if (ORIGIN_WHITELIST.includes(req.headers.origin)) {
console.log('header OK!');
return next(req, res);
} else {
console.log('header wrong!');
res.status(403);
res.end('game over');
}
}

我尝试在pages/api的下一个连接设置中使用它们,在那里我定义了onError和onNoMatch选项:

// factory fn returns new instance of newConnect with default setup
function factory() {
return nextConnect({
onError(err, req, res) {
console.log('error?:', Object.keys(err));
res.status(500).json({ message: 'Internal Server Error' });
},
onNoMatch(req, res) {
res.status(405).json({ message: `Method ${req.method} is not allowed.` });
},
});
}
// pages/api/subscribe.js 
export default factory()
.use(validateOriginHeader)
.use(validateEmail)
.post(async (req, res) => {
try {
const mailchimpRes = await mailchimp.subscribe(req.body);
res.json(mailchimpRes);
} catch (e) {
res.json(e);
}
});

问题:

只有第一个中间件执行(打印'header OK!'在服务器控制台)。validateEmail中的Console永远不会打印。当我控制台错误在onError处理程序中定义的下一个连接选项,它看起来像请求对象,即。它包含正文和电子邮件有效负载。

调用路由的结果是500:返回内部服务器错误(在onError处理程序中定义)。

这个设置有什么问题?

版本使用:

"next"11.1.2"next-connect"0.10.2">

您必须使用空参数调用next()而不是next(req, res)。带参数调用next()会得到onError

最新更新