在 Sails js 中调用 REST API [英] Call REST API in Sails js
本文介绍了在 Sails js 中调用 REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 Sails js.我不知道如何调用 REST api 并获取响应数据.
Im using Sails js. I dont know how to call a REST api and get the response data.
我的控制器:
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);
}
};
我无法获得响应数据,sails.log.debug() 没有在控制台上显示任何内容.
I cant get the response data, the sails.log.debug() didnt show anything on the console.
它只在浏览器上显示Helo Some".
It only shows "Helo Someone" on the browser.
推荐答案
您可能想看看新的 request-promise api,它非常易于使用,并且在错误处理和性能的情况下提供更好的控制.https://github.com/request/request-promise
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...
});
这篇关于在 Sails js 中调用 REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文