JSON响应并在Express中调用next() [英] JSON response and calling next() in Express

查看:70
本文介绍了JSON响应并在Express中调用next()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用Express 4将JSON响应发送到前端以指示存在错误,并可以在Express中间件内部调用next(err),以便可以通过服务器呢?还是这些通话是完全互斥的?

Is it possible, using Express 4, to send a JSON response to the front-end indicating that there was an error, as well as calling next(err) inside the Express middleware, so that the error can be handled by the server as well? Or are these calls completely mutually exclusive?

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

My current assumption is that you can do this:

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 });
});

推荐答案

它们不是互斥的.例如(代替中间件,我使用路由处理程序进行演示,但是两者的原理相同):

They aren't mutually exclusive. For example (instead of middleware I'm using route handlers to demonstrate, but the principle is the same for both):

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以确保已发送响应(否则,错误处理程序应自行发送).

You could check res.headersSent in the error handler to make sure that a response is sent (if not, the error handler should send one itself).

这篇关于JSON响应并在Express中调用next()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆