how to find request parameters in 'nodejs'

2019-03-25 09:47发布

问题:

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.

回答1:

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.