express + pug中的动态URL

问题描述 投票:1回答:1

我有一个简单的表单,它返回POST上的用户名。

form(method='POST',action='./users/:username')
    div(class='form-group')
        label(for="username") Username;
        input(class='form-control' type="text" id='username' name='username')
        button(class="btn btn-default") Submit

这个路由器迎接用户:

router.post('/users/:username', function (req , res){
    var username = req.body.username;
    res.send("Hi " + username);
});

除了URL显示“http://localhost:3000/users/:username”而不是在表单中输入的用户名外,一切正常。我错过了什么?

javascript node.js express pug
1个回答
0
投票

A direct solution

呈现视图的路径需要将变量传递给它。例如:

路由器:

// this is not the POST request, this is the initial render of the view
router.get("/users/:username", function(req, res) {
    res.render("viewPath", { username: req.params.username });
    // of course, replace the 'viewPath' with the actual path to your view
});

视图:

form(method='POST', action='./users/' + username)

A logical solution

正如评论建议的那样,你不需要POST路线中的/:username。您可以省略它,因为用户名是在正文中传递的。你可以这样做:

router.post('/users', function (req, res) {
    var username = req.body.username;
    res.send("Hi " + username);
});
© www.soinside.com 2019 - 2024. All rights reserved.