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 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.