在Node.js中,除了使用子进程进行CURL调用之外,是否有一种方法可以对远程服务器REST API进行CURL调用并获得返回数据?
我还需要设置远程REST调用的请求头,以及在GET(或POST)中查询字符串。
我找到了这个:http://blog.nodejitsu.com/jsdom-jquery-in-5-lines-on-nodejs
但是它没有显示任何POST查询字符串的方法。
在Node.js中,除了使用子进程进行CURL调用之外,是否有一种方法可以对远程服务器REST API进行CURL调用并获得返回数据?
我还需要设置远程REST调用的请求头,以及在GET(或POST)中查询字符串。
我找到了这个:http://blog.nodejitsu.com/jsdom-jquery-in-5-lines-on-nodejs
但是它没有显示任何POST查询字符串的方法。
当前回答
如何使用请求-简化HTTP客户端。
2020年2月编辑:请求已弃用,所以你可能不应该再使用它了。
这是一个GET:
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body) // Print the google web page.
}
})
OP也想要一个帖子:
request.post('http://service.com/upload', {form:{key:'value'}})
其他回答
如何使用请求-简化HTTP客户端。
2020年2月编辑:请求已弃用,所以你可能不应该再使用它了。
这是一个GET:
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body) // Print the google web page.
}
})
OP也想要一个帖子:
request.post('http://service.com/upload', {form:{key:'value'}})
您可以使用curlrequest轻松设置请求的时间…你甚至可以在选项中设置头信息来“伪造”浏览器调用。
警告:截至2020年2月11日,请求已完全弃用。
另一个例子-你需要为此安装请求模块
var request = require('request');
function get_trustyou(trust_you_id, callback) {
var options = {
uri : 'https://api.trustyou.com/hotels/'+trust_you_id+'/seal.json',
method : 'GET'
};
var res = '';
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
res = body;
}
else {
res = 'Not Found';
}
callback(res);
});
}
get_trustyou("674fa44c-1fbd-4275-aa72-a20f262372cd", function(resp){
console.log(resp);
});
2022年更新:
从node.js v18版本开始,你可以使用全局可用的获取API(参见https://nodejs.org/en/blog/announcements/v18-release-announce/)
在他们的公告页面上还有一个用法示例:
const res = await fetch('https://nodejs.org/api/documentation.json');
if (res.ok) {
const data = await res.json();
console.log(data);
}
我没有找到任何cURL,所以我写了一个node-libcurl包装器,可以在https://www.npmjs.com/package/vps-rest-client上找到。
POST是这样的:
var host = 'https://api.budgetvm.com/v2/dns/record';
var key = 'some___key';
var domain_id = 'some___id';
var rest = require('vps-rest-client');
var client = rest.createClient(key, {
verbose: false
});
var post = {
domain: domain_id,
record: 'test.example.net',
type: 'A',
content: '111.111.111.111'
};
client.post(host, post).then(function(resp) {
console.info(resp);
if (resp.success === true) {
// some action
}
client.close();
}).catch((err) => console.info(err));