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: 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.
1 Answer
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); 3