brownzilla
brownzilla

Reputation: 289

Cannot read property 'send' of undefined

I'm trying to send data to the router from an external script and it returns the error TypeError: Cannot read property 'send' of undefined

Here is the code

app.js

var Cake = require('./modules/cake');

router.get('/cakes', function(req, res) {
  Cake.getCake();
})

cake.js

module.exports = {
  getCake: function (req, res) {
    request({
      url: "http://get.cakes/json",
      json: true
    }, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        res.send(body);
      }
    });
  }
};

Take note that http://get.cake/ isn't a real site. It's irrelevent to the question.

Upvotes: 3

Views: 26980

Answers (1)

nem035
nem035

Reputation: 35501

You're not passing req and res down to getCake

router.get('/cakes', function(req, res) {
  Cake.getCake(); // <-- you're passing nothing here so `res` is undefined within `getCake` and so you're calling `undefined.send()`
})

You should have:

router.get('/cakes', function(req, res) {
  Cake.getCake(req, res); // <-- pass `req` and `res` down to `getCake`
})

Or even shorthand:

router.get('/cakes', Cake.getCake);

Upvotes: 10

Related Questions