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

I am using Express v3.4.4. When I try to do like this:

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

I get an error message:

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

In code, worker:

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

does not work:

  workflow.on('someEvent', function () { var cb = res.send; cb({ error: null, result: 'Result' }); }); 
+5
source share
2 answers

send actually a function of the res object. He tries to use other data from the object res . But when you do

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

you simply use the send function object without reference to the res object. That is why it does not work.


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

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

Now

 cb({...}); 

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

The bind function is actually Function.prototype.bind

+6
source

This is because in JavaScript, the value of this inside the method is bound to the contained object.

  • The call to res.send() makes this value inside the send res function.
  • In contrast, when invoking an unrelated version of cb() , this not expected.

The internal implementation of Express.js is based on the fact that this is related and most likely contains an expression such as this.method that raises a TypeError: Cannot read property 'method' of undefined error.

0
source

Source: https://habr.com/ru/post/1245975/


All Articles