javascript 如何在 express(node.js) 中获取路径变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31055347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:11:10  来源:igfitidea点击:

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

javascriptnode.jsexpress

提问by Qasim Khokhar

I am trying to get value of path variable "userId"using req.paramsbut 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,

我正在尝试使用req.params获取路径变量“userId”的值,但我得到了undefined,如果有人可以指导我解决这个问题,我将非常感谢他。我把我的代码放在下面。我已经经历了一些例子,但这些例子也是这样做的,我不知道我的代码出了什么问题。 谢谢,

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

回答by michelem

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

我认为你的路线错了,你不能路由到/user/:userId/group和发布/是没有意义的。我的意思是要获取userId参数,您应该发布到/user/:userId/group

Route file route.js:

路线文件route.js

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

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

Controller file controller.js:

控制器文件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());
});