2012-05-01 11 views
5

In Node.js (utilizzando Express.js), quando chiamo http.request come ad esempio:http.get e query string in node.js

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

tutto va bene, tranne la query parte delle opzioni viene ignorato . La documentazione dice che la stringa di query deve essere costruita manualmente e passata all'interno di path: qualcosa come path: '/?name=John%20Doe&age=50'.

Qual è il modo migliore per farlo? query è un semplice hash di stringa -> {stringa, numero}.

risposta

15

Quello che stai cercando è la querystring biblioteca http://nodejs.org/api/querystring.html

E anche, si potrebbe essere interessati a questa biblioteca richiesta client HTTP 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=' 
+0

funziona come per magia, grazie – user124114

+0

Grazie! Mi ha salvato la vita nel crunch. – Yablargo

+0

cosa dire di JSON.stringify? –