Skip to content Skip to sidebar Skip to footer

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 cl

Solution 1:

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

diagram.router.js

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

The next change is in the index function itself. The function gets two parameters by express: req - the request object and res - the response object:

diagram.controller.js

module.exports.index = functionindex(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.

Post a Comment for "How To Pass Data From Controller To Router In Node.js?"