javascript - Express+pug 中的动态 URL

标签 javascript node.js express pug

我有一个简单的表单,可以在 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/

相关文章:

javascript - 将图像与 GIF 合并 - FFMPEG

javascript - jQuery.text() 不适用于 textarea 元素

Javascript typeof 抛出引用错误

javascript - 是否有包含一组丰富的非常高级的常用函数的 javascript 库?

java - 如何发出 HTTPS GET 请求来与其他方竞争并尝试成为最快的?

javascript - s.replace 不是sequelize.fn 'AVG' 上的函数

node.js - 处理/防止潜在的恶意请求(AWS、Node.js)

javascript - NodeJS 和 Express - 导出函数跳过 SQLite3 DB 查询

node.js - 类型错误 : Cannot read property 'showMessageBox' of undefined electron in node js

node.js - 无法从 Heroku 上托管的 Express 应用程序设置 cookie