larz larz - 6 months ago 12
Node.js Question

GET in a Route - Nodejs

what´s the best way if I want to make a GET request in a route?

api.js

api.route('/guests')
.get(function(req, res) {
Guest.find(function(err, guests) {
if (err)
res.send(err);

res.json(guests);
});
});


routes.js

app.get('/export', requiresLogin, function(req, res) {

/* make a GET request to my api (eg.: 'api/guests') */
/* and save the 'guests' to a variable */

});

Answer

First Solution

Instead of calling internal apis, you can define a controller guestCtrl.js and call the function from guestCtrl.js in api.js and routes.js

guestCtrl.js

module.exports = {
   getGuests : function(){
      Guest.find(function(err, guests) {
         if (err)
            //handle error
            return [];
         else
            return guests;
       });
   }
}

api.js

//path of guests.js
var guestCtrl = require('guestCtrl.js');

api.route('/guests').get(function(req, res) {
     return guestCtrl.getGuests();
});

routes.js

var guestCtrl = require('guestCtrl.js');
app.get('/export', requiresLogin, function(req, res) {
    var guests = guestsCtrl.getGuests();
    // do whatever you like to do with guests
});

Second Solution

If you really want to work with internal api, then you can use request module.

e.g.

routes.js

var request = require('request');
app.get('/export', requiresLogin, function(req, res) {
   // you can put the hostname and port here 
   request('http://127.0.0.1:3000/api/guests', function(err, body, response){
       var guests = body; // and save the 'guests' to a variable        
   });

});