Search code examples
expressurlparametersroutes

res.render() doesn't add parameter to URL


I'd like Express to send a user back to their account page, if there is an error when they are trying to edit their account details.

The account page loads up fine. The problem is, the URL doesn't include the user ID.

So, my URL looks like: https://website.com/account

And I would like it to look like, for example: https://website.com/account/16

Code for the "reload" of the account page looks like:

    databaseInstance.updateUser(req.session.user.id, req.session.user.email, valuesToUpdate).then((didUpdate) => {
    const updateErrors = [];
    if (didUpdate instanceof Error) {
        updateErrors.push("There was an error when saving your changes.");
    } else {
        // Update session here
    }
    res.render(`account`, {
        path: `/account/${req.session.user!.id}`,
        pageTitle: "Account",
        isAuthenticated: req.session.isLoggedIn || false,
        user: req.session.user || undefined,
        userOnPage: req.session.user,
        errors: updateErrors,
        form: {
            "username": null,
            "email": null,
            "email-confirm": null,
            "password": null,
            "password-confirm": null,
        },
    });

Route looks like:

router.get("/account/:userId", getAccount);

I also tried it with res.render called as follows:

        res.render(`account/${req.session.user!.id}`, {
        path: `/account/${req.session.user!.id}`,
        pageTitle: "Account",

Which just caused 500 server error :/ Read the docs ofc but can't see any other way to put the param in there.

Does anybody know how to do this off the top of your head?


Solution

  • Figured it out. Render function has nothing to do with the URL, it just changes the HTML on the page. The form I used to submit changes is the URL that's being used in the address bar. So I used JS to change the URL on the account page, once res.render occurred.

    Reference: https://stackoverflow.com/a/32221099/5633214