[英]How to pass json object from controller to router?
I have a data in controller from mongodb now i want to send this json object to router so i can send to client side using api , with below code i am getting an error TypeError: Cannot read property 'json' of undefined
Any idea what is implemented wrong ? 我现在有一个来自mongodb的控制器中的数据,我想将此json对象发送到路由器,以便我可以使用api发送到客户端,使用以下代码,我收到一个错误TypeError: Cannot read property 'json' of undefined
任何想法实行错了吗?
controller.js 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 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;
I think the module.exports
(see my comment above) is the problem. 我认为module.exports
(请参阅上面的评论)是问题所在。 What do you think about writing your request handling straightforward first (so that you have a feeling of success (: ): 您对首先编写直接处理的请求有什么看法(以便您有成功的感觉(:):
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);
Advanced version 进阶版
controller.js 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 router.js
const express = require('express');
const controller = require('./controller');
const router = express.Router();
router.get('/getAllDiagram', controller.index);
module.exports = router;
app.js app.js
const express = require('express');
const router = require('./router');
const app = express();
app.use(router);
app.listen(8080);
Important: Please check the module.exports.index
declaration. 重要:请检查module.exports.index
声明。 That was wrong in your code snippet. 这在您的代码片段中是错误的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.