Search code examples
node.jsexpresshttp-redirectrequest-response

response.redirect() with parameters


I want to redirect to a page where the path is like /users/home/:id

   response.redirect('/users/home')

The above code will redirect to /users/home but I want to redirect it to a page like '/users/home/1' dynamically with parameters. How shall I solve it?Do explain with some examples


Solution

  • You could use template literals to form the new url, for example:

    app.get("/users/home/:id", (req, res) => { 
        res.redirect(`/users/alternate_home/${req.params.id}`);
    });
    
    app.get("/users/alternate_home/:id", (req, res) => { 
        res.json(users);
    });