1

In my express app, I'm trying to create a helper function that sends a response so that I don't have to keep typing it. However, I'm having problems getting this to work. I keep getting this as undefined.

function sendMessage(code, message)
{
  return this.res.status(code).json({message});
}

app.('/foo', (req, res) => {
  return sendMessage(200, 'bar');
});

app.('/buzz', (req, res) => {
  return sendMessage(200, 'bang');
});
treyBake
  • 6,440
  • 6
  • 26
  • 57
Ryan
  • 23
  • 3
  • 2
    Possible duplicate of [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Liam Mar 01 '19 at 11:44
  • `sendMessage.call({req, res}, 200, 'bang')`? – Bergi Mar 01 '19 at 11:48

4 Answers4

1

this won't solve your problem.

res is not a property of any object, it is a variable.

You need to pass it to your function:

function sendMessage(res, code, message)
{
  return res.status(code).json({message});
}

app.('/foo', (req, res) => {
  return sendMessage(res, 200, 'bar');
});
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

try this

function sendMessage(res, {status,data})
{
  return res.status(status).json(data)
}

app.('/foo', (req, res) => {
  return sendMessage(res,{ status : 200, data :  'bar'});
});


sathish kumar
  • 1,477
  • 1
  • 11
  • 18
0

Express doesn't use dynamic this, in order to access needed middleware parameters they should be passed to a function, as other answers show.

If the intention is to provide a middleware with custom response, higher-order function can be used with optional code argument:

const createSendMessageMiddleware = (message, code = 200) => (req, res) => {
  res.status(code).json({message});
}

app.get('/foo', createSendMessageMiddleware('bar'));

app.get('/buzz', createSendMessageMiddleware('bang'));
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
0
 function sendMessage(code, message,res) {
      return res.send({code:code,message:message});
    }

    app.('/foo', (req, res) => {

    return sendMessage(200, 'bar',res);
    });

    app.('/buzz', (req, res) => {

    return sendMessage(200, 'bang',res);
    });