提交 HTML 表单并使用 FETCH API 处理 PUT 请求后页面未重定向的问题

问题描述 投票:0回答:1

在提交 HTML 表单并处理 PUT 请求后,页面不会重定向。我遇到的问题涉及大量代码,因此请就某些事情的作用提出澄清问题。我将在这里粘贴我认为可能与我的问题相关的任何代码。

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

我遇到的问题与编辑个人资料有关。 GET 方法工作正常,PUT 的数据处理也工作正常,但是当我尝试在没有任何反应后进行页面重定向时。

getEditProfile(这会将用户引导至个人资料编辑器页面,他们可以在其中编辑其帐户信息):

  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(这将 HTML (EJS) 表单提交作为 PUT 请求处理,因为 HTML 表单本身仅支持 GET 和 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(这会调用 updateUser() 来编辑帐户数据,并尝试将用户重定向回其个人资料页面,但它仍保留在个人资料编辑器页面上):

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

最后的页面重定向该如何处理?我已经尝试了很多不同的策略和研究,但由于某种原因似乎没有任何效果。 Docker 给出的状态代码为 302

我希望页面在 put 请求之后重定向到 /profile

javascript node.js express fetch-api put
1个回答
-1
投票

为了更好地了解幕后发生的情况,您是否尝试过嗅探 http 流量? 这个想法是查看发送/接收了哪些http标头,并检查重定向是否发送“太晚”,例如在服务器已经回复一些其他响应之后,因此丢弃任何进一步的重定向。 如果您在 Unix (Linux/MacOS) 下工作,像 ngrep 这样的简单工具就可以嗅探 http 流量。 恕我直言,拥有一份成绩单非常有用。

© www.soinside.com 2019 - 2024. All rights reserved.