【问题标题】:Override every res.render to res.json in the whole app将整个应用程序中的每个 res.render 覆盖为 res.json
【发布时间】:2021-11-08 20:17:45
【问题描述】:

我想将整个应用程序的每个 res.render 转换为 res.json。我这样做的原因是为了避免错误代码,因为仅在开发环境中,我想返回 JSON 而不是 HTML。

我发现了这个 question 并关注了 solution 我认为它可以使用:

const renderToJson = function(req, res, next) {
  res.render = function(view, options, callback) {
    res.status(200).json(res, view, options, callback);
  };
};
app.use(renderToJson);

或者

const renderToJson = function(req, res, next) {
  const _render = res.status(200).json;
  res.render = function(view, options, callback) {
    _render.call(res, view, options, callback);
  };
};
app.use(renderToJson);

但不幸的是它没有。我继续收到没有错误的 HTML。

【问题讨论】:

    标签: node.js express middleware


    【解决方案1】:

    我可以得到我想要的东西

    const renderToJson = function(req, res, next) {
      let _render = res.render;
      res.render = function(view, options, callback) {
        this.json(options);
      };
      next();
    };
    app.use(renderToJson);
    

    保持我的回复不被批准,因为这样做可能会有缺点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 2016-06-26
      相关资源
      最近更新 更多