Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS Express. res.send() fails when assigned to another var

I'm using Express v3.4.4. When i try to do like this:

var cb = res.send;
cb(result);

I get an error:

   ...\node_modules\express\lib\response.js:84
   var HEAD = 'HEAD' == req.method;
   TypeError: Cannot read property 'method' of undefined

In code, working one:

    workflow.on('someEvent', function () {
      res.send({
          error: null,
          result: 'Result'
        });
    }); 

not working:

    workflow.on('someEvent', function () {
      var cb = res.send; 
      cb({
          error: null,
          result: 'Result'
      });
    });    
like image 629
c4off Avatar asked Mar 29 '16 10:03

c4off


1 Answers

The send is actually a function of the object res. It tries to use other data from the res object. But, when you do

var cb = res.send;
cb({...});

you are simply using the function object send without the reference to the res object. That is why it is not working.


If you ever need to do something like that, then bind the res object to the send function like this

var cb = res.send.bind(res);

now

cb({...});

will also work. Because the res is bound to the send function object and the resulting function is stored in cb.

The bind function actually is Function.prototype.bind

like image 198
thefourtheye Avatar answered Nov 13 '22 15:11

thefourtheye