简体   繁体   中英

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 ?

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;

I think the module.exports (see my comment above) is the problem. 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

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);

Important: Please check the module.exports.index declaration. That was wrong in your code snippet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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