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

旧街凉风 提交于 2020-06-25 11:30:12

问题


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());
});

回答1:


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());
});


来源:https://stackoverflow.com/questions/31055347/how-to-get-path-variable-in-expressnode-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!