Basically you'll want to wait for your request to fire its callback and then feed the fetched data into res.locals
. Assuming you are fetching JSON data, you could do this:
// api/controllers/SomeController.js
test: function(req, res) {
var https = require('https');
...
https.request(options, function(response) {
var responseData = '';
response.setEncoding('utf8');
response.on('data', function(chunk){
responseData += chunk;
});
response.once('error', function(err){
// Some error handling here, e.g.:
res.serverError(err);
});
response.on('end', function(){
try {
// response available as `responseData` in `yourview`
res.locals.requestData = JSON.parse(responseData);
} catch (e) {
sails.log.warn('Could not parse response from options.hostname: ' + e);
}
res.view('yourview');
});
}).end();
}
The example code you supplied has some issues:
test: function(res,req) ...
Don't mixup the controller arguments, the first is _req_uest, the second one _res_ponse.var req = https.request ...
You really do not want to override thereq
argument passed into your controller action. Use some other name.https.request(options, function(res) {...}
Same here. Doing this overridesres
for thehttps.request
callback scope - preventing you from using all the goodies (e.g.:res.view
) supplied by theres
parameter passed to your controller.
I'd guess it would make sense for you to read up on closures and callbacks: