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}.
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 : "?
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='
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With