How to use external rest api in Sails js (nodejs MVC)

让人想犯罪 __ 提交于 2019-12-04 07:45:01
marionebl

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 the req argument passed into your controller action. Use some other name.

  • https.request(options, function(res) {...} Same here. Doing this overrides res for the https.request callback scope - preventing you from using all the goodies (e.g.: res.view) supplied by the res parameter passed to your controller.

I'd guess it would make sense for you to read up on closures and callbacks:

What are Closures and Callbacks?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!