Reputation: 2135
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
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
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