最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to iterate over body of POST request in Express.js? - Stack Overflow

programmeradmin0浏览0评论

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] not req.params(key) Or possibly for(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
Add a ment  | 

1 Answer 1

Reset to default 4

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.

发布评论

评论列表(0)

  1. 暂无评论