Reputation: 43491
I'm using Node.js and I want to see all of the parameters that have been posted to my script. To get to my function, in my routes/index.js
I'm doing:
app.post('/v1/order', order.create);
Then in my function, I have:
exports.create = function(req, res, next) {
console.log( req.params );
But it's returning an empty array. But when I do:
exports.create = function(req, res, next) {
console.log( req.param('account_id') );
I get data. So I'm a bit confused as to what's going on here.
Upvotes: 32
Views: 46833
Reputation: 11
Add this for your server.js
or app.js
:
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
Upvotes: 1
Reputation: 767
With postman, you can have two types of get requests:
x-www-form-urlencoded
and passing data through the body.You can always use this code snippet to always capture the data, no matter how you pass it.
/*
* Email can be passed both inside a body of a json, or as
a parameter inside the url.
* { email: '[email protected]' } -> [email protected]
* http://localhost/buyer/get/[email protected] -> [email protected]
*/
let { email }: { email?: string } = req.query;
if (!email) email = req.body.email;
console.log(email);
Upvotes: 1
Reputation: 868
I had a similar problem and thought I'd post the solution to that for those coming here for the same reason. My req.params was coming out as an empty object because I declared the URL variable in the parent route. The solution is to add this option to the router:
const router = express.Router({ mergeParams: true });
Upvotes: 30
Reputation: 3723
req.params
can only get the param of request url in this pattern:/user/:name
req.query
get query params(name) like /user?name=123
or body params.
Upvotes: 67
Reputation: 6824
req.params only contain the route params, not query string params (from GET) and not body params (from POST). The param() function however checks all three, see:
http://expressjs.com/4x/api.html#req.params
Upvotes: 38