furyfish
furyfish

Reputation: 2135

Call REST API in Sails js

Im using Sails js. I dont know how to call a REST api and get the response data.

My Controller:

var request = require('request');
var http = require('http');
var https = require('https');

module.exports = {
    main: function(req, res){
        var rs = "Someone";
        var options = {
            hostname: 'thomas-bayer.com',
            port: 80,
            path: '/sqlrest',
            method: 'GET'
        };

        http.request(options, function(response) {      
            sails.log.debug('log:'+response);
            rs = response;
        });

        res.send("Hello "+ rs);
    }
};

I cant get the response data, the sails.log.debug() didnt show anything on the console.

It only shows "Helo Someone" on the browser.

Upvotes: 4

Views: 4118

Answers (2)

WizofOz
WizofOz

Reputation: 119

You might like to take a look at new request-promise api it is very easy to use and provide better control in case of error handling and performance. https://github.com/request/request-promise

Install 
npm install --save request
npm install --save request-promise

Usage 
    var rp = require('request-promise');
    var options = {
      uri: 'https://api.github.com/user/repos',
      qs: {
        access_token: 'xxxxx xxxxx' // -> uri + '?access_token=xxxxx%20xxxxx'
      },
      headers: {
        'User-Agent': 'Request-Promise'
      },
      json: true // Automatically parses the JSON string in the response
    };

    rp(options)
      .then(function(repos) {
        console.log('User has %d repos', repos.length);
      })
      .catch(function(err) {
        // API call failed...
      });

Upvotes: 3

hlozancic
hlozancic

Reputation: 1499

http.request is asynchronous.

Just wrap your res.send inside callback like this:

var request = require('request');
var http = require('http');
var https = require('https');

module.exports = {
    main: function(req, res){
        var rs = "Someone";
        var options = {
            hostname: 'thomas-bayer.com',
            port: 80,
            path: '/sqlrest',
            method: 'GET'
        };

        http.request(options, function(response) {      
            sails.log.debug('log:'+response);
            rs = response;

            res.send(rs);
        });


    }
};

Upvotes: 1

Related Questions