【问题标题】:Restify: "override" default nextRestify:“覆盖”默认下一个
【发布时间】:2016-04-26 06:43:36
【问题描述】:

我想在 Restify 中覆盖下一个默认值。例如。现在我有类似的代码

server.post('/names', function (req, res, next) {
  names = req.params.names;
  if (!Array.isArray(names)) {
    return next(new restify.errors.BadRequestError('names field is wrong or missing'));
  }
  res.send({ code: "OK" });
  return next();
});

我希望它只是

server.post('/names', function (req, res, next) {
  names = req.params.names;
  if (!Array.isArray(names)) {
    return next(new restify.errors.BadRequestError('names field is wrong or missing'));
  }
  // Add names to DB
  return next();
});

next(对于非错误结果)是这样的

function next(res) {
  if (!body.hasOwnProperty("code")) {
    body["code"] = "OK";
  }
  res.send(body);
}

实现这一点的最佳方法是什么?

【问题讨论】:

  • 您的代码在每个变量声明中都缺少 var 关键字。这很糟糕,因为没有var,一切都会变得全球化。仔细检查您的代码,每个没有var 的变量声明都是等待发生的错误。 jshint 之类的工具有助于发现这些错误。
  • 除此之外,您的问题还不清楚。不要解释你认为代码应该是什么样子,解释你想要实现什么。
  • 这只是草图。这个想法只是将结果对象发送到最后一个 next 而不是 res.send + next。

标签: javascript node.js restify


【解决方案1】:

我认为您可能正在寻找在链中所有其他处理程序完成后执行的处理程序。考虑“之后”事件处理程序。他们在文档中显示an example for audit logging

您应该能够根据需要使用相同的东西来更新响应正文。代码可能看起来像这样......

server.on('after', function (request, response, route, error) {});

请记住,这仍然需要您从链中的所有其他处理程序中return next();

【讨论】:

  • 不错的选择。谢谢!
猜你喜欢
  • 2015-06-24
  • 2014-12-12
  • 2011-12-20
  • 1970-01-01
  • 2018-07-11
  • 2020-07-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多