0

I'm looking for a way to get the query string part of a url using node.js or one of it's extension module. I've tried using url and express but they give me an array of parameters. I want to original string. Any ideas ?

example; for:

http://www.mydom.com?a=337&b=33

give me

a=337&b=33

(with or without the ?)

Dani
  • 14,639
  • 11
  • 62
  • 110
  • Not sure but are u looking for req.query.a || req.query.b ?? – swapnesh Nov 22 '15 at 20:14
  • just the query part (all the string, not just the params. url.parse gives and object that the .search property gives the answer. – Dani Nov 22 '15 at 20:21

2 Answers2

4

Use url.parse. By default it will return an object whose query property is the query string. (You can pass true as the second argument if you want query to be an object instead, but since you want a string the default is what you want.)

var url = require('url');

var urlToParse = 'http://www.mydom.com/?a=337&b=33';
var urlObj = url.parse(urlToParse);

console.log(urlObj.query);
// => a=337&b=33
Jordan Running
  • 102,619
  • 17
  • 182
  • 182
  • [`req.originalUrl`](http://expressjs.com/4x/api.html#req.originalUrl) can be the `urlToParse`. (Or, [`req.url`](https://nodejs.org/api/http.html#http_message_url) when you aren't using Express.) – Jonathan Lonowski Nov 22 '15 at 20:17
  • actually it was urlObj.search that gave me the solution. both you and @Touffy are correct using the parse tool. the .query gives me an array of params. for the string I used .search. – Dani Nov 22 '15 at 20:20
1

How about using the built-in url.parse method?

Touffy
  • 6,309
  • 22
  • 28