简体   繁体   English

将Node.JS res传递给函数?

[英]Passing Node.JS res to a function?

This doesn't show any response to an HTTP request, just hangs: 这不会显示对HTTP请求的任何响应,只会挂起:

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

This works: 这有效:

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

I'm using restify with this simple function: 我正在通过以下简单功能使用restify:

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

I'm not so good at ES6 but I guess that it may be the javascript's context problem (I mean the this variable). 我不太擅长ES6,但我想可能是javascript的上下文问题(我的意思是this变量)。

In your case, res.json() may throw res is not defined (I guess) since the this at that moment is the context of export const to_end ... (thanks to => 's magic), which does not know what is res . 在您的情况下, res.json()可能会抛出res is not defined (我想),因为此时的thisexport const to_end ... (由于=>的魔力)的上下文,它不知道什么是res

Sorry for my terribly bad explanation :(. Read this to understand more about this . 对不起,我的解释很糟糕:(。阅读这篇文章以了解更多有关this

We can make things simpler: 我们可以使事情变得更简单:

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

P/S: Not tested yet. P / S:尚未测试。 Good luck! 祝好运! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM