我正在尝试从外部脚本向路由器发送数据,并返回错误TypeError: Cannot read property 'send' of undefined
这是代码
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);
}
});
}
};
请注意http://get.cake/
不是真实的网站。这个问题无关紧要。
答案 0 :(得分:5)
您没有将req
和res
传递给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()`
})
你应该:
router.get('/cakes', function(req, res) {
Cake.getCake(req, res); // <-- pass `req` and `res` down to `getCake`
})
甚至是速记:
router.get('/cakes', Cake.getCake);