I'm constructing a generic route handler for POST requests in NodeJS.
I need to iterate over the req.params
of the POST request, without knowing beforehand what the parameters are.
I have tried the following without success:
console.log("checking param keys...")
Object.keys(req.param).forEach(function(key){
console.log(key +"is " + req.params(key) )
})
When I run this code, only the "Checking param keys..." gets printed.
Anybody knows how to do this?
I'm constructing a generic route handler for POST requests in NodeJS.
I need to iterate over the req.params
of the POST request, without knowing beforehand what the parameters are.
I have tried the following without success:
console.log("checking param keys...")
Object.keys(req.param).forEach(function(key){
console.log(key +"is " + req.params(key) )
})
When I run this code, only the "Checking param keys..." gets printed.
Anybody knows how to do this?
Share Improve this question edited Mar 26, 2019 at 19:31 ivanleoncz 10.1k7 gold badges61 silver badges51 bronze badges asked Feb 25, 2014 at 2:27 Anders MartiniAnders Martini 9482 gold badges14 silver badges34 bronze badges 3-
i think you mean
req.params[key]
notreq.params(key)
Or possiblyfor(var key in req.param) { ... }
– Mouseroot Commented Feb 25, 2014 at 2:29 - in the future when in doubt it may help todo a console.dir to give you a better view of an object, while debugging – Mouseroot Commented Feb 25, 2014 at 2:43
- Thanks for your ideas Mouseroot, your are right! by simply logging req to the console and then logging those keys one by one I managed to figure out that the form keys are actually in req.body, not req.param as one might think...Edited post to include solution! Cant believe I didnt think of that earlier! =P – Anders Martini Commented Feb 25, 2014 at 2:44
1 Answer
Reset to default 4I guess you're asking how to iterate form post from a url encoded POST request body, so it is bodyParser() middleware that did your trick.
req.params
is an array that contains properties mapped by routing defined express app. see details from req.params, not the request body. Take the follow code for example:
var app = require("express")();
app.use(express.bodyParser());
app.post("/form/:name", function(req, res) {
console.log(req.params);
console.log(req.body);
console.log(req.query);
res.send("ok");
});
Then test it like this:
$ curl -X POST --data 'foo=bar' http://localhost:3000/form/form1?url=/abc
You will see the console output like this:
[ name: 'form1' ]
{ foo: 'bar' }
{ url: '/abc' }
So req.body
is the right way to access request body, req.query
is for read query string of all HTTP methods.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745205244a4616563.html
评论列表(0条)