Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get path variable in express(node.js)

I am trying to get value of path variable "userId" using req.params but i am getting undefined, if any one can guide me in this problem i ll be very thankful to him. i have place my code below. i have go through some example but those examples are also doing in this way i don't know what is going wrong with my code.
thank you,

parent router for controller

app.use("/user/:userId/group",groupController);

Action In Controller

Router.post("/", function (req, res, next) {

    var group = new Group(req.body);

    console.log(req.params);

    group.userId = req.params.userId;

    group.save(new dataCallbacks(req, res, next, "Group").insert());
});
like image 308
Qasim Khokhar Avatar asked Jun 25 '15 16:06

Qasim Khokhar


1 Answers

I think you are wrong with your route, you can't route to /user/:userId/group and post to / that doesn't make sense. I mean to get userIdparam, you should post to /user/:userId/group:

Route file route.js:

var ctrl = require('controller.js');

app.route('/user/:userId/group').post(ctrl.doIt);

Controller file controller.js:

exports.doIt = function(req, res, next) {
    var group = new Group(req.body);

    console.log(req.params);

    group.userId = req.params.userId;

    group.save(new dataCallbacks(req, res, next, "Group").insert());
});
like image 61
michelem Avatar answered Oct 10 '22 08:10

michelem