【问题标题】:JSON response and calling next() in ExpressJSON 响应并在 Express 中调用 next()
【发布时间】:2015-06-27 06:02:35
【问题描述】:

是否可以使用 Express 4 向前端发送 JSON 响应指示出现错误,以及在 Express 中间件内部调用 next(err),以便错误可以由服务器也是?还是这些调用完全相互排斥?

我目前的假设是你可以这样做:

app.get('/', function(req, res, next) {
  res.json({ error : true });
});

你可以这样做:

app.get('/', function(req, res, next) {
  next(new Error('here goes the error message');
});

但你不能这样做

app.get('/', function(req, res, next) {
  res.json({ error : true });
  next(new Error('here goes the error message');
});

你不能这样做:

app.get('/', function(req, res, next) {
  next(new Error('here goes the error message');
  res.json({ error : true });
});

【问题讨论】:

  • 你能提供一些示例代码吗?
  • @kdbanman 喜欢什么?看起来像发送 json 然后调用 next.
  • “以便服务器也可以处理错误”是什么意思?
  • @DaveNewton 这是一个关于函数调用兼容性的问题,所以包含显示他想要如何使用它们的代码不是更好吗?它消除了歧义。它使帮助变得更容易。这表明已经投入了一些努力。 (这是一个合法的问题 - 你有很多代表和元活动,而我没有。)
  • 我添加了一些代码作为示例,但如果@robertklep 是正确的,那么这将回答问题

标签: node.js express


【解决方案1】:

它们不是相互排斥的。例如(我使用路由处理程序来演示,而不是中间件,但两者的原理是相同的):

app.get('/', function(req, res, next) {
  res.json({ error : true });
  next(new Error('something happened'));
});

app.get('/another', function(req, res, next) {
  next(new Error('something happened'));
});

app.use(function(err, req, res, next) {
  console.error(err);
  if (! res.headersSent) {
    res.send(500);
  }
});

您可以在错误处理程序中检查res.headersSent 以确保已发送响应(如果没有,错误处理程序应自行发送)。

【讨论】:

  • 酷,让我试一试,很长时间以来我都认为它们是独家的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-03
  • 1970-01-01
  • 2023-01-31
  • 2014-06-07
  • 2016-05-07
  • 1970-01-01
相关资源
最近更新 更多