Search code examples
javascriptnode.jsexpresspug

Dynamic URL in express+pug


I have a simple form which returns the username on 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

This router greets user :

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

Everything works fine execpt the URL shows "http://localhost:3000/users/:username" instead of the username entered in form. What am i missing?


Solution

  • A direct solution

    The route that renders the view needs to pass a variable to it. For example:

    Router:

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

    View:

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

    A logical solution

    As a comment suggested, you don't need the /:username in the POST route. You can omit it, as the username is passed in the body. You can just do:

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