Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: How to pass params in a POST?

I have an express app and a POST route:

app.post('/test', function(req, res){

 //res.send(req.body.title + req.body.body)
 console.log(req.params);
 console.log(req.body);
 console.log(req.body.user);
 console.log(req.body.feedback);
 console.log("ok");
 //return;
});

I try to do ~ $ curl -X POST "http://xxxx.herokuapp.com/test?user=hello" and I get:

TypeError: Cannot read property 'user' of undefined
    at Router.<anonymous> (/app/app.js:40:22)
    at done (/app/node_modules/express/lib/router/index.js:250:22)
    at middleware (/app/node_modules/express/lib/router/index.js:244:9)
    at param (/app/node_modules/express/lib/router/index.js:227:11)
    at pass (/app/node_modules/express/lib/router/index.js:232:6)
    at Router._dispatch (/app/node_modules/express/lib/router/index.js:255:4)
    at Object.handle (/app/node_modules/express/lib/router/index.js:45:10)
    at next (/app/node_modules/express/node_modules/connect/lib/http.js:198:15)
    at Object.methodOverride [as handle] (/app/node_modules/express/node_modules/connect/lib/middleware/methodOverride.js:35:5)
    at next (/app/node_modules/express/node_modules/connect/lib/http.js:198:15)~ $ 

Shouldn't that POST work?

Thanks

like image 631
donald Avatar asked May 25 '26 12:05

donald


2 Answers

No, the parameter you are passing is not on the post body but in the querystring.

According to the docs, to access it you must do:

req.query.user
like image 167
Pablo Fernandez Avatar answered May 27 '26 01:05

Pablo Fernandez


The selected answer is wrong. It's very clear you wanted something from the request body (given that you say POST), not the query string. You need to make sure the body parser is in your middleware stack:

app.use(express.bodyParser());

Once you do this, you can use req.body.

(Furthermore, as others have mentioned, your curl is wrong as well. You're putting something in the query string there instead of the request body.)

like image 32
chjj Avatar answered May 27 '26 01:05

chjj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!