You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

next-connect链式调用中间件触发onError返回500错误问题排查

问题原因

你的中间件调用next()的方式不符合next-connect的约定:
next-connect遵循Express中间件规范,next()函数如果传入任意参数,都会被框架判定为主动抛出错误,直接触发全局onError回调,不会继续执行后续中间件。
你在validateOriginHeader和validateEmail两个中间件校验通过后,都写了return next(req, res),这里传入的第一个参数req会被当成错误对象传入onError,所以才会出现你观测到的现象:

  • 仅第一个中间件执行,打印header OK!后直接进入错误处理
  • onError中拿到的err实际是请求对象
  • 接口直接返回500错误

修复方案

将两个中间件中带参数的next(req, res)调用改为无参数调用即可,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!');
    // 改为无参数调用next
    return next();
  } 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!');
    // 改为无参数调用next
    return next();
  } else {
    console.log('header wrong!');
    res.status(403);
    res.end('game over');
  }
}

修改后即可按预期依次执行两个中间件,校验通过后进入POST接口处理逻辑。

内容的提问来源于stack exchange,提问作者mtx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 08:18:01