最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot read property 'send' of undefined - Stack Overflow

programmeradmin3浏览0评论

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: "/json",
      json: true
    }, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        res.send(body);
      }
    });
  }
};

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

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.

Share Improve this question edited Dec 14, 2016 at 3:39 brownzilla asked Dec 14, 2016 at 3:32 brownzillabrownzilla 2892 gold badges3 silver badges12 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

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);
发布评论

评论列表(0)

  1. 暂无评论