Parse url encoded body with Restify
Asked Answered
M

1

5

I'm not able to do url encoded posts to my node.js API using restify. I have the following setup of my restify app:

app.use(restify.acceptParser(app.acceptable));                                  
app.use(restify.queryParser());                                                 
app.use(restify.urlEncodedBodyParser());

But when I'm requesting my app using curl with the following request:

curl -X POST -H "Content-type: application/x-www-form-urlencoded" -d quantity=50 http://app:5000/feeds

I get the following input body in my view:

console.log(req.body)  // "quantity=50"

Thanks in advance,

Mattias

Medawar answered 3/1, 2014 at 10:16 Comment(0)
S
13

The default setup for Restify places parsed parameters in req.params. This is done by both the queryParser and the different bodyParser middlewares.

So to access the quantity parameter, use req.params.quantity.

If you really want to use req.body instead, you need to pass mapParams : false to the bodyParser constructor:

app.use(restify.plugins.urlEncodedBodyParser({ mapParams : false }));

Now req.body will contain the parsed parameters.

Sacramental answered 3/1, 2014 at 10:37 Comment(3)
The moment I use the parser my entire service becomes unresponsive on any URL. It simply never returns and no breakpoints are hitStonyhearted
@ChristianBongiorno that's usually a sign that the middleware isn't passing the requests along the middleware chain. This answer is pretty old, perhaps something changed since then that may cause the behaviour you're witnessing.Sacramental
I discovered that independently but you are/were correct. The CORS module was stopping the whole thing. Honestly, restify is not really impressing me.Stonyhearted

© 2022 - 2024 — McMap. All rights reserved.