Call REST API in Sails js

流过昼夜 提交于 2019-12-05 20:50:50

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...
      });

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);
        });


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