在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查询字符串的方法。
当前回答
如果你有Node.js 4.4+,看看reqclient,它允许你以cURL风格进行调用和记录请求,所以你可以很容易地在应用程序之外检查和重现调用。
返回Promise对象,而不是传递简单的回调函数,所以你可以以一种更“时尚”的方式处理结果,轻松地链接结果,并以一种标准的方式处理错误。还删除了每个请求的大量样板配置:基本URL、超时、内容类型格式、默认标头、URL中的参数和查询绑定,以及基本缓存特性。
这是一个如何初始化它的例子,调用并记录curl样式的操作:
var RequestClient = require("reqclient").RequestClient;
var client = new RequestClient({
baseUrl:"http://baseurl.com/api/", debugRequest:true, debugResponse:true});
client.post("client/orders", {"client": 1234, "ref_id": "A987"},{"x-token": "AFF01XX"});
这将登录到控制台…
[Requesting client/orders]-> -X POST http://baseurl.com/api/client/orders -d '{"client": 1234, "ref_id": "A987"}' -H '{"x-token": "AFF01XX"}' -H Content-Type:application/json
当返回响应时……
[Response client/orders]<- Status 200 - {"orderId": 1320934}
这是一个如何处理promise对象的响应的例子:
client.get("reports/clients")
.then(function(response) {
// Do something with the result
}).catch(console.error); // In case of error ...
当然,它可以用:npm install reqclient安装。
其他回答
警告:截至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);
});
使用最新的Async/Await特性
https://www.npmjs.com/package/request-promise-native
npm install --save request
npm install --save request-promise-native
/ /代码
async function getData (){
try{
var rp = require ('request-promise-native');
var options = {
uri:'https://reqres.in/api/users/2',
json:true
};
var response = await rp(options);
return response;
}catch(error){
throw error;
}
}
try{
console.log(getData());
}catch(error){
console.log(error);
}
如果你有Node.js 4.4+,看看reqclient,它允许你以cURL风格进行调用和记录请求,所以你可以很容易地在应用程序之外检查和重现调用。
返回Promise对象,而不是传递简单的回调函数,所以你可以以一种更“时尚”的方式处理结果,轻松地链接结果,并以一种标准的方式处理错误。还删除了每个请求的大量样板配置:基本URL、超时、内容类型格式、默认标头、URL中的参数和查询绑定,以及基本缓存特性。
这是一个如何初始化它的例子,调用并记录curl样式的操作:
var RequestClient = require("reqclient").RequestClient;
var client = new RequestClient({
baseUrl:"http://baseurl.com/api/", debugRequest:true, debugResponse:true});
client.post("client/orders", {"client": 1234, "ref_id": "A987"},{"x-token": "AFF01XX"});
这将登录到控制台…
[Requesting client/orders]-> -X POST http://baseurl.com/api/client/orders -d '{"client": 1234, "ref_id": "A987"}' -H '{"x-token": "AFF01XX"}' -H Content-Type:application/json
当返回响应时……
[Response client/orders]<- Status 200 - {"orderId": 1320934}
这是一个如何处理promise对象的响应的例子:
client.get("reports/clients")
.then(function(response) {
// Do something with the result
}).catch(console.error); // In case of error ...
当然,它可以用:npm install reqclient安装。
警告:截至2020年2月11日,请求已完全弃用。
如果你使用form-data实现,更多信息请访问https://tanaikech.github.io/2017/07/27/multipart-post-request-using-node.js):
var fs = require('fs');
var request = require('request');
request.post({
url: 'https://slack.com/api/files.upload',
formData: {
file: fs.createReadStream('sample.zip'),
token: '### access token ###',
filetype: 'zip',
filename: 'samplefilename',
channels: 'sample',
title: 'sampletitle',
},
}, function (error, response, body) {
console.log(body);
});
看看http.request
var options = {
host: url,
port: 80,
path: '/resource?id=foo&bar=baz',
method: 'POST'
};
http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
}).end();