我有一个简单的表单,可以在 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 ”而不是表单中输入的用户名。 我错过了什么?
最佳答案
直接解决方案
渲染 View 的路由需要向其传递一个变量。例如:
路由器:
// 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)
合乎逻辑的解决方案
正如评论所建议的,您不需要在 POST 路由中使用 /:username
。您可以省略它,因为用户名是在正文中传递的。你可以这样做:
router.post('/users', function (req, res) {
var username = req.body.username;
res.send("Hi " + username);
});
关于javascript - Express+pug 中的动态 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50993348/