shantanu
shantanu

Reputation: 2008

how to pass query string object in http.request in nodejs

I already have a request object. Now all i have to do is change the host and make http request again.
//URL type : www.something.com/a/b?w=2&e=2

fun(req,res){

 options = {
   host : <newhost>
   method : req.method
   path : req.path
   headers : req.headers
  }
  http.request(options,...)
}

Now how do i send query string(w=2&e=2) in this option.
I can do it using request module(in nodejs) but that follows redirect(HTTP 302) as well.

Thanks,
Shantanu

Upvotes: 1

Views: 12937

Answers (2)

AlphaCrow
AlphaCrow

Reputation: 21

A better way is to stringify an object with nodes querystring module. This way you can pass an options object to a custom queryBuilder function and reuse it for multiple requests of varying values. Here is a basic example.

    var querystring = require('querystring');
    var http = require('http');

    var options = {
        host : 'www.host.com',
        path : ''
    }

    var queryBuilder = function (object, callback) {
        callback(querystring.stringify(object));
    };

    queryBuilder({ w: '2', e: '2' }, callback(data){
        options.path = data;
        http.request(options, function (req, res) {
            //do something with the response
        }).end();
    });

this will set the path equal to w=2&e=2

Upvotes: 2

Kamrul
Kamrul

Reputation: 7311

http can do this as well

var queryString = 'w=2&e=2';
options = {
   host : <newhost>
   method : req.method
   path : req.path + '?' + queryString // say, var queryString = 'w=2&e=2'  
   headers : req.headers
  }
  http.request(options,...)

Upvotes: 2

Related Questions