Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js http 'get' request with query string parameters

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); }); 

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 method saves the work of building own URL. But ideally the request will be higher level than this also.

like image 287
djechlin Avatar asked Jun 03 '13 18:06

djechlin


People also ask

How do you pass parameters in GET request node js?

The GET request is sent by calling the request method of the http module. Various options for the GET request can be set through a parameter. const http = require('http'); const querystring = require('querystring'); // GET parameters const parameters = { id: 123, type: "post" } // GET parameters as query string : "?

How do I pass a query string in node js?

The query parameter is the variable whose value is passed in the URL in the form of key-value pair at the end of the URL after a question mark (?). For example, www.geeksforgeeks.org? name=abc where, 'name' is the key of query parameter whose value is 'abc'. We just create a folder and add a file as index.

CAN GET method have query parameters?

When the GET request method is used, if a client uses the HTTP protocol on a web server to request a certain resource, the client sends the server certain GET parameters through the requested URL. These parameters are pairs of names and their corresponding values, so-called name-value pairs.


1 Answers

Check out the request module.

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); }); 
like image 69
Daniel Avatar answered Sep 20 '22 08:09

Daniel