【问题标题】:Passing Node.JS res to a function?将 Node.JS res 传递给函数?
【发布时间】:2016-02-12 03:21:54
【问题描述】:

这不会显示对 HTTP 请求的任何响应,只是挂起:

function middleware(req, res, next) {
    to_end(res).NotFound();
    return next();
}

这行得通:

function middleware(req, res, next) {
    to_end(res).NotFound();
    res.send(); // <----------------------------------------------
    return next();
}

我正在使用带有这个简单功能的 restify:

export const to_end = res => {
    return {
        NotFound: (entity = 'Entity') => res.json(404, {
            error: 'NotFound', error_message: `${entity} not found`
        })
    }
}

【问题讨论】:

    标签: javascript node.js parameter-passing connect restify


    【解决方案1】:

    我不太擅长 ES6,但我猜这可能是 javascript 的上下文问题(我的意思是 this 变量)。

    在你的情况下,res.json() 可能会抛出res is not defined(我猜)因为那一刻的thisexport const to_end ... 的上下文(感谢=&gt; 的魔法),它不知道是什么是res

    抱歉,我的解释非常糟糕 :(。阅读 this 以了解有关 this 的更多信息。

    我们可以让事情变得更简单:

    module.exports = function(res) {
      return {
        NotFound: function() {
          res.json(404, {
            error: 'NotFound', 
            error_message: `${entity} not found`
          });
        }
      }
    };
    

    P/S:尚未测试。祝你好运! :)

    【讨论】:

      猜你喜欢
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-04
      • 1970-01-01
      • 2017-10-19
      • 1970-01-01
      相关资源
      最近更新 更多