node.js带有查询字符串参数的http'get'请求 [英] node.js http 'get' request with query string parameters

查看:142
本文介绍了node.js带有查询字符串参数的http'get'请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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'请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆