Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

http.get and query string in node.js

In Node.js (using Express.js), when I call http.request like such:

var options = {
    host: '127.0.0.1',
    port: 80,
    path: '/',
    query: {name: "John Doe", age: 50} // <---- problem here
};
http.request(options, function(response) { ... });

all is well, except the query part of options is ignored. Documentation says the query string must be constructed manually, and passed inside path: something like path: '/?name=John%20Doe&age=50'.

What is the best way to achieve that? query is a simple hash of string->{string, number}.

like image 931
user124114 Avatar asked May 01 '12 10:05

user124114


People also ask

How do I get HTTP request parameters in 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 : "?


1 Answers

What you're looking for is the querystring library http://nodejs.org/api/querystring.html

And also, you might be interested in this HTTP client request library https://github.com/mikeal/request

var qs = require('querystring');
qs.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' })
// returns
'foo=bar&baz=qux&baz=quux&corge='
like image 185
250R Avatar answered Oct 19 '22 00:10

250R