Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send an http get request with parameters in Node.js

I'm trying to send a GET request from a Node.js app to a Rails server. Currently, I am using the request module like so:

var request = require("request");
var url = 'www.example.com'

function sendRequest(url){
  string = 'http://localhost:3000/my-api-controller?url=' + url;
  request.get(string, function(error, response, body){
    console.log(body);
  });
}

This works. But what I would like is not to build the string for a get request, but to pass parameters of the request as a javascript object (in a jQuery-like fashion). There is one example on the wiki page of the request module that uses exactly this kind of syntax:

request.get('http://some.server.com/', {
  'auth': {
    'user': 'username',
    'pass': 'password',
    'sendImmediately': false
  }
});

However, when I tried to adapt this syntax for my purposes like so:

function sendRequest(url){
  request.get('http://localhost:3000/my-api-controller', {url: url}, function(error, response, body){
    console.log(body);
  });
}

the url parameter did not get sent.

So my question is, am I doing something wrong here or does the request module not support passing parameters of a get request as a javascript object? And if it doesn't, could you suggest a handy Node module that does?

like image 772
azangru Avatar asked Apr 14 '15 00:04

azangru


2 Answers

The "HTTP Authentication" example you point to in the request module does not build a query string, it adds authentication headers based on specific options. There's another part of that page that describes what you want:

request.get({url: "http://localhost:3000/my-api-controller", 
             qs: {url: url}},
            function(error, response, body){
               console.log(body);
            });

Something like that. This, in turn, uses the querystring module to build the query string, as was mentioned in the comments.

like image 193
skagedal Avatar answered Oct 13 '22 01:10

skagedal


The object provided to request() or its convenience methods isn't just for data parameters.

To provide { url: url } to be sent in the query-string, you'll want to use the qs option.

request.get('http://localhost:3000/my-api-controller', {
    qs: { url: url }
}, function(error, response, body){
    // ...
});
like image 20
Jonathan Lonowski Avatar answered Oct 13 '22 01:10

Jonathan Lonowski