在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查询字符串的方法。
当前回答
const http = require('http');
const url = process.argv[2];
http.get(url, function(response) {
let finalData = "";
response.on("data", function (data) {
finalData += data.toString();
});
response.on("end", function() {
console.log(finalData.length);
console.log(finalData.toString());
});
});
其他回答
我使用节点获取,因为它使用熟悉的(如果你是一个web开发人员)fetch() API。fetch()是从浏览器发出任意HTTP请求的新方法。
是的,我知道这是一个节点js的问题,但我们不希望减少API的开发者必须记住和理解的数量,并提高我们的javascript代码的可重用性吗?Fetch是一个标准,所以我们收敛一下如何?
fetch()的另一个好处是它返回一个javascript Promise,所以你可以像这样编写异步代码:
let fetch = require('node-fetch');
fetch('http://localhost', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: '{}'
}).then(response => {
return response.json();
}).catch(err => {console.log(err);});
获取超级种子XMLHTTPRequest。这里有更多信息。
我一直在使用restler进行webservices调用,工作起来很有魅力,而且很整洁。
使用最新的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);
}
const http = require('http');
const url = process.argv[2];
http.get(url, function(response) {
let finalData = "";
response.on("data", function (data) {
finalData += data.toString();
});
response.on("end", function() {
console.log(finalData.length);
console.log(finalData.toString());
});
});
您可以使用curlrequest轻松设置请求的时间…你甚至可以在选项中设置头信息来“伪造”浏览器调用。