C B
C B

Reputation: 13344

Nodejs, Express GET POST params

I'm new to Node/Express.. I see GET params can be captured like so:

app.get('/log/:name', api.logfunc);

POST like so:

app.post('/log', ... (form variables available in req.body.)

I'm aware of app.all, but is there a single way I can get all the variables for GET and POST when using app.all? (I'm too used to $_REQUEST in php!:)

thx,

Upvotes: 11

Views: 15273

Answers (2)

pirs
pirs

Reputation: 2461

Personnaly, i merge req.params, req.body, req.query in one single object req.props with Object.assign()

in ES6:

You just need to write this in your route:

   app.all('/myroute/:myparam', (req, res, next) => {
        // merge all req data in one
        req.props = Object.assign(req.query, req.params, req.body);
        // optional :
        // delete req.query;
        // delete req.params;
        // delete req.body;
    });

In ES5:

    app.all('/myroute/:myparam', function(req, res, next){
        // merge all req data in one
        req.props = {};
        if(req.query)  for (var attrname in req.query)  { req.props[attrname] = req.query[attrname]; }
        if(req.params) for (var attrname in req.params) { req.props[attrname] = req.params[attrname]; }
        if(req.body)   for (var attrname in req.body)   { req.props[attrname] = req.body[attrname]; }
        // optional :
        // delete req.query;
        // delete req.params;
        // delete req.body;
    });

Now, you can access easily to your GET, POST, PUT params with req.props in all your routes, be careful about similars name if you decide to delete the old req.

Also, you can do a middleware/functions to make it more useful yet.

More about Object.assign(): https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/assign

Upvotes: 0

ebohlman
ebohlman

Reputation: 15003

You're dealing with three different methods of parameter-passing:

1) Path parameters, which express's router captures in req.param when you use colon-prefixed components or regex captures in your route. These can be present in both GET and POST requests.

2) URL query-string parameters, which will be captured in req.query if you use the express.query middleware. These can also be present in both GET and POST requests.

3) Body parameters, which will be captured in req.body if you use the express.bodyParser middleware. These will only be present in POST requests that have a Content-Type of "x-www-form-urlencoded".

So what you need to do is to merge all three objects (if they exist) into one. There are no native Object methods for doing this, but there are lots of popular workarounds. For example, the underscore.js library defines an extend function, which would allow you to write

req.params=_.extend(req.params || {}, req.query || {}, req.body || {}).

If you don't want to use a library and want to roll your own way of extending objects, take a look at this blog post.

Upvotes: 24

Related Questions