我有一个Node.js应用程序,它是一个http客户端(目前)。所以我在做:
I have a Node.js application that is an http client (at the moment). So I'm doing:
var query = require('querystring').stringify(propertiesObject); http.get(url + query, function(res) { console.log("Got response: " + res.statusCode); }).on('error', function(e) { console.log("Got error: " + e.message); });这似乎是一个很好的方法来实现这一目标。但是我有点恼火,我不得不做 url + query 步骤。这应该由一个公共库封装,但我没有看到它存在于节点的 http 库中,我不确定标准的npm包可以实现它。是否有一种相当广泛使用的方式更好?
This seems like a good enough way to accomplish this. However I'm somewhat miffed that I had to do the url + query step. This should be encapsulated by a common library, but I don't see this existing in node's http library yet and I'm not sure what standard npm package might accomplish it. Is there a reasonably widely used way that's better?
url.format 方法保存了构建自己的URL的工作。但理想情况下,请求的级别也会高于此。
url.format method saves the work of building own URL. But ideally the request will be higher level than this also.
推荐答案查看 request 模块。
它比node的内置http客户端更全面。
It's more full featured than node's built-in http client.
var request = require('request'); var propertiesObject = { field1:'test1', field2:'test2' }; request({url:url, qs:propertiesObject}, function(err, response, body) { if(err) { console.log(err); return; } console.log("Get response: " + response.statusCode); });更多推荐
node.js带有查询字符串参数的http'get'请求
发布评论