如何在express(node.js)中获取路径变量 [英] How to get path variable in express(node.js)
问题描述
我正在尝试使用 req.params 来获取路径变量"userId" 的值,但是我得到了 undefined (如果有的话)指导我解决这个问题,我将非常感谢他.我将我的代码放在下面.
我已经看过一些示例,但是那些示例也在以这种方式运行,我不知道我的代码出了什么问题.
谢谢你,
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,
控制器的父路由器
app.use("/user/:userId/group",groupController);
控制器中的动作
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());
});
推荐答案
我认为您的路线有误,无法路由至/user/:userId/group
并发布至/
这没有任何意义.我的意思是要获取userId
param,您应该发布到/user/:userId/group
:
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 userId
param, you should post to /user/:userId/group
:
路由文件route.js
:
var ctrl = require('controller.js');
app.route('/user/:userId/group').post(ctrl.doIt);
控制器文件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());
});
这篇关于如何在express(node.js)中获取路径变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!