2011-04-13 161 views
134

Node.js的,比使用子进程,使卷曲通话外,有没有办法让远程服务器调用CURL REST API并获得返回的数据?如何在Node.js中进行远程REST调用?任何CURL?

我还需要设置请求标头到远程REST调用,以及GET(或POST)中的查询字符串。

我觉得这是一个:http://blog.nodejitsu.com/jsdom-jquery-in-5-lines-on-nodejs

但它并不显示任何发布方式查询字符串。

+0

我写了这个https://github.com/jonataswalker/vps-rest-client – 2016-09-28 10:57:29

回答

159

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(); 
+3

所以,即使它是POST,我也在查询字符串追加数据? – murvinlai 2011-04-13 18:28:47

+3

@murvinlai不确定。去阅读文档,来源,HTTP规范。不是该地区的专家。 – Raynos 2011-04-13 19:09:50

+0

版本6.18文档:http://nodejs.org/docs/v0.6.18/api/http.html#http_http_request_options_callback – weisjohn 2012-06-15 14:58:59

29

http://isolasoftware.it/2012/05/28/call-rest-api-with-node-js/

var https = require('https'); 

/** 
* HOW TO Make an HTTP Call - GET 
*/ 
// options for GET 
var optionsget = { 
    host : 'graph.facebook.com', // here only the domain name 
    // (no http/https !) 
    port : 443, 
    path : '/youscada', // the rest of the url with parameters if needed 
    method : 'GET' // do GET 
}; 

console.info('Options prepared:'); 
console.info(optionsget); 
console.info('Do the GET call'); 

// do the GET request 
var reqGet = https.request(optionsget, function(res) { 
    console.log("statusCode: ", res.statusCode); 
    // uncomment it for header details 
// console.log("headers: ", res.headers); 


    res.on('data', function(d) { 
     console.info('GET result:\n'); 
     process.stdout.write(d); 
     console.info('\n\nCall completed'); 
    }); 

}); 

reqGet.end(); 
reqGet.on('error', function(e) { 
    console.error(e); 
}); 

/** 
* HOW TO Make an HTTP Call - POST 
*/ 
// do a POST request 
// create the JSON object 
jsonObject = JSON.stringify({ 
    "message" : "The web of things is approaching, let do some tests to be ready!", 
    "name" : "Test message posted with node.js", 
    "caption" : "Some tests with node.js", 
    "link" : "http://www.youscada.com", 
    "description" : "this is a description", 
    "picture" : "http://youscada.com/wp-content/uploads/2012/05/logo2.png", 
    "actions" : [ { 
     "name" : "youSCADA", 
     "link" : "http://www.youscada.com" 
    } ] 
}); 

// prepare the header 
var postheaders = { 
    'Content-Type' : 'application/json', 
    'Content-Length' : Buffer.byteLength(jsonObject, 'utf8') 
}; 

// the post options 
var optionspost = { 
    host : 'graph.facebook.com', 
    port : 443, 
    path : '/youscada/feed?access_token=your_api_key', 
    method : 'POST', 
    headers : postheaders 
}; 

console.info('Options prepared:'); 
console.info(optionspost); 
console.info('Do the POST call'); 

// do the POST call 
var reqPost = https.request(optionspost, function(res) { 
    console.log("statusCode: ", res.statusCode); 
    // uncomment it for header details 
// console.log("headers: ", res.headers); 

    res.on('data', function(d) { 
     console.info('POST result:\n'); 
     process.stdout.write(d); 
     console.info('\n\nPOST completed'); 
    }); 
}); 

// write the json data 
reqPost.write(jsonObject); 
reqPost.end(); 
reqPost.on('error', function(e) { 
    console.error(e); 
}); 

/** 
* Get Message - GET 
*/ 
// options for GET 
var optionsgetmsg = { 
    host : 'graph.facebook.com', // here only the domain name 
    // (no http/https !) 
    port : 443, 
    path : '/youscada/feed?access_token=you_api_key', // the rest of the url with parameters if needed 
    method : 'GET' // do GET 
}; 

console.info('Options prepared:'); 
console.info(optionsgetmsg); 
console.info('Do the GET call'); 

// do the GET request 
var reqGet = https.request(optionsgetmsg, function(res) { 
    console.log("statusCode: ", res.statusCode); 
    // uncomment it for header details 
// console.log("headers: ", res.headers); 


    res.on('data', function(d) { 
     console.info('GET result after POST:\n'); 
     process.stdout.write(d); 
     console.info('\n\nCall completed'); 
    }); 

}); 

reqGet.end(); 
reqGet.on('error', function(e) { 
    console.error(e); 
}); 
+1

我如何访问d的值? d = {“data”:[{“id”:1111,“name”:“peter”}]}。如何获得名称价值? – peter 2013-02-18 12:58:31

+2

设法通过使用var thed = JSON.parse(d)获取值; \t \t console.log(“the id is:”+ thed.data [0] .id); \t \t 但有些时候,我得到“意外的输入结束” – peter 2013-02-19 07:52:44

10

我一直在使用restler制作Web服务调用,就像魅力,是非常整洁。

1

您可以使用curlrequest轻松设置你想做的事......你可以在选项甚至套头为“”浏览器什么时候打电话的请求。

64

如何使用Request — Simplified HTTP client

这里有一个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也想要一个POST:

request.post('http://service.com/upload', {form:{key:'value'}}) 
+0

在google.com上正常工作,但在请求facebook的图表api时返回“RequestError:Error:socket挂断”。请指导,谢谢! – 2017-06-28 16:04:40

+0

这个模块包含很多问题! – 2017-11-10 14:24:25

+0

如何以这种方式使用REST API传递请求参数? – vdenotaris 2018-02-25 11:18:07

3

一个另一个例子 - 你需要安装请求模块为

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); 
}); 
3
var http = require('http'); 
var url = process.argv[2]; 

http.get(url, function(response) { 
    var finalData = ""; 

    response.on("data", function (data) { 
    finalData += data.toString(); 
    }); 

    response.on("end", function() { 
    console.log(finalData.length); 
    console.log(finalData.toString()); 
    }); 

}); 
3

我没有发现任何与卷曲,所以我写了一个包装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)); 
1

如果你有Node.js的4.4+,看看reqclient,它允许你拨打电话和登录卷曲风格的要求,因此您可以轻松地在应用程序外部检查和再现呼叫。

返回Promise对象,而不是通过简单的回调,所以你可以在一个更“时尚”方式处理结果,chain结果很容易,并以标准的方式处理错误。还为每个请求删除了许多样板配置:基本URL,超时,内容类型格式,默认标题,URL中的参数和查询绑定以及基本缓存功能。

这是如何初始化,拨打电话并与卷曲风格的登录操作的例子:

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} 

This是如何处理与该承诺对象的响应的示例:npm install reqclient

client.get("reports/clients") 
    .then(function(response) { 
    // Do something with the result 
    }).catch(console.error); // In case of error ... 

当然,它可以与被安装。

18

我使用node-fetch,因为它使用熟悉的(如果您是网络开发人员)fetch() API。 fetch()是从浏览器发出任意HTTP请求的新方法。

是的我知道这是一个节点js的问题,但我们不是想减少API的开发人员必须记住和理解的数量,并提高我们的JavaScript代码的可重用性吗? Fetch is a standard那我们如何汇合呢?

有关获取其他好处()是返回一个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。这里有一些more info

相关问题