how to find request parameters in 'nodejs'
Asked Answered
M

2

14

when i sent a request to nodejs server,

how can we find the parameters sent in the request query when request sent to nodejs server.

req.param

req.params

req.query

all giving undefined.

also when i stringify req request it gives error :

Converting circular structure to JSON

How to find query parameters.

Menado answered 4/9, 2013 at 11:16 Comment(2)
What kind of request? req.body contains the body (data) for POST requests.Sensationalism
here i am talking about get request for firstMenado
A
14

You can use the url module:

$ npm install url

And then something like this:

var http = require("http");
var url = require("url");

http.createServer(function(req, res) {

  var parsedUrl = url.parse(req.url, true); // true to get query as object
  var queryAsObject = parsedUrl.query;

  console.log(JSON.stringify(queryAsObject));

  res.end(JSON.stringify(queryAsObject));

}).listen(8080);

console.log("Server listening on port 8080");

Test in your browser:

http://localhost:8080/?a=123&b=xxy

For POST requests you can use bodyParser.

Acth answered 4/9, 2013 at 11:45 Comment(1)
url is deprecated since node 11, you should use new URLDonalt
B
1

Since url.parse() is deprecated and new URL() does not accept relative links, here is what we are supposed to use nowadays I assume:

/api/some-action?param1=foo&param2=bar

const { pathname, searchParams } = new URL(req.url!, "x://x");
const param1 = searchParams.get("param1");
const param2 = searchParams.get("param2");

"x://x" is just a dummy base url to make new URL() work for a relative url which req.url is.

Buonaparte answered 8/12, 2023 at 14:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.