简体   繁体   English

如何在 node.js 中将数据从控制器传递到路由器?

[英]How to pass data from controller to router in node.js?

I have folder diagram where i have two files controller and router , Now i have pulled the data from mongodb in controller that i am trying to pass it router so i can send it to client using api but i am failed to get response in router , any idea what is implemented wrong.我有文件夹图,其中有两个文件控制器和路由器,现在我已经从控制器中的 mongodb 中提取数据,我试图将其传递给路由器,以便我可以使用 api 将其发送到客户端,但我无法在路由器中获得响应,知道什么是错误的。

I mentioned folder diagram because this router is just for this particular model that will send response regarding diagram only.我提到了文件夹diagram因为这个路由器只是针对这个特定的模型,它只会发送关于图的响应。

diagram.controller.js图控制器.js

var Diagram = require('./diagram.model');
var mongoose = require('mongoose');
module.exports = function index() {
       Diagram.find({}, function(err, res) {
         if (!err) {
           console.log('Response from controller', res);
           return res;
         }
       });
     }

diagram.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;

You have to modify your code a little bit.你必须稍微修改你的代码。

The first aspect that has to be changed is the way how you pass the index function to the router.必须更改的第一个方面是将index函数传递给路由器的方式。 Please make sure that you don't execute it directly.请确保您不直接执行它。 This function will be called by express when a request hits your server at the particular route.当请求在特定路由上到达您的服务器时,此函数将被express调用。

diagram.router.js图.router.js

router.get('/getAllDiagram', controller.index);

The next change is in the index function itself.下一个变化是index函数本身。 The function gets two parameters by express : req - the request object and res - the response object:该函数通过express获取两个参数: req - 请求对象和res - 响应对象:

diagram.controller.js图控制器.js

module.exports.index = function index(req, res) {
    Diagram.find({}, function(err, result) {
        if (err) {
            console.error('Something bad happened: ' + err.message);

            return res.status(500);
        }

        console.log('Response from controller', result);
        res.json(result);
    });
};

Please note that I renamed your variable res to result .请注意,我将您的变量res重命名为result

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM