Problem with page not redirecting after submitting an HTML form and handling PUT request with FETCH API

40 views Asked by At

I'm having a problem where the page won't redirect after submitting an HTML form and handling a PUT request. The issue I'm having involves a lot of code, so please ask clarifying questions about what certain things do. I will paste any code I feel may be relevant to my issue here.

Routing in route.js file:

/* Profile Router */
router.route("/profile").get((req, res, next) => {
  Authorize.auth(req, res, next, "GET profile");
}, PagesController.getProfile);

/* Edit Profile Router */
router
  .route("/edit-profile")
  .get((req, res, next) => {
    Authorize.auth(req, res, next, "GET edit-profile");
  }, PagesController.getEditProfile)
  .put((req, res, next) => {
    Authorize.auth(req, res, next, "PUT edit-profile");
  }, PagesController.putEditProfile);

The issue I'm having pertains to edit-profile. The GET method works fine, and the data handling for PUT works as well, but when I try to have the page redirect after nothing happens.

getEditProfile (this directs the user to the profile editor page, where they can edit their account information):

  static async getEditProfile(req, res, next) {
    try {
      const user = await UsersAccessor.getRegisteredByUsername(Authorize.getUsername(req));
      
      res.render("edit_profile", {
        name: user.username,
        role: user.role,
        year: user.information.year,
        major: user.information.major,
        bio: user.information.bio,
      });
    } catch (e) {
      return handleError(res, Errors[500].DataGET);
    }
  }

edit_profile.js (this handles the HTML (EJS) form submission as a PUT request, since HTML forms natively only support GET and POST):

document.addEventListener('DOMContentLoaded', function() {
    const form = document.querySelector('form');

    form.addEventListener('submit', async function(event) {
        event.preventDefault();

        // Get form data
        const formData = new FormData(form);

        // Convert form data to JSON
        const jsonData = {};
        formData.forEach((value, key) => {
            jsonData[key] = value;
        });

        try {
            // Make PUT request to update profile
            const response = await fetch(window.location.href, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(jsonData),
            });

            if (!response.ok) {
                throw new Error('Failed to update profile');
            }

            window.location.href = '/profile';

        } catch (error) {
            console.error(error.message);
        }
    });
});

putEditProfile (this calls updateUser() to edit the account data, and attempts to redirect the user back to their profile page, but instead it stays on the profile editor page):

  static async putEditProfile(req, res, next) {
    try {
      // Update the user information
      const updatedUser = {
        username: req.body.name,
        role: req.body.role,
        information: {
          year: req.body.year,
          major: req.body.major,
          bio: req.body.bio,
          image: req.body.image,
        },
      };
  
      // Update the password if provided (might be a nifty feature for the future)
      if (req.body.password) {
        updatedUser.password = await bcrypt.hash(req.body.password, 10);
      }

      // Update the user in the database
      const updatedUserData = await UsersAccessor.updateUser(updatedUser);
      if (!updatedUserData) {
        // Handle case where the user is not found
        return handleError(res, Errors[404].UserNotFound);
      }

      res.redirect("/profile");
    } catch (e) {;
      console.log(e);
      return handleError(res, Errors[500].DataPUT);
    }
  }

How should I handle the page redirection at the end? I already tried a lot of different strategies and research but nothing seems to work for some reason. Docker gives a status code of 302.

I expected the page to redirect to /profile following the put request.

0

There are 0 answers