我在mongodb的控制器中有一个数据现在我想将这个json对象发送到路由器,所以我可以使用api发送到客户端,下面的代码我收到错误TypeError: Cannot read property 'json' of undefined
任何想法是什么实施错误?
controller.js
var Diagram = require('./diagram.model');
var mongoose = require('mongoose');
module.exports = function index(req,res) {
Diagram.find({}, function(err, result) {
if (!err) {
console.log('Response from controller', result);
return res.json(result);
}
});
}
router.js
var express = require('express');
var controller = require('./diagram.controller');
var router = express.Router();
console.log('THis is in router',controller.index);
router.get('/getAllDiagram',controller.index);
module.exports = router;
答案 0 :(得分:2)
我认为module.exports
(见上面的评论)就是问题所在。您如何看待首先直接处理请求的处理(以便您有成功感受:():
const express = require('express');
const app = express();
app.get('/getAllDiagram', (req, res) => {
Diagram.find({}, function(err, result) {
if (err) {
console.error(`Error in finding diagram: ${err.message}`);
return res.status(500);
}
res.json(result);
});
});
app.listen(8080);
高级版
controller.js
const Diagram = require('./diagram.model');
module.exports.index = (req, res) => {
Diagram.find({}, function(err, result) {
if (err) {
console.error(`Error in finding diagram: ${err.message}`);
return res.status(500);
}
res.json(result);
});
};
router.js
const express = require('express');
const controller = require('./controller');
const router = express.Router();
router.get('/getAllDiagram', controller.index);
module.exports = router;
app.js
const express = require('express');
const router = require('./router');
const app = express();
app.use(router);
app.listen(8080);
重要提示:请检查module.exports.index
声明。这在您的代码段中是错误的。