【问题标题】:Router.push is not redirecting me; Nextjs with Express serverRouter.push 没有重定向我; Nextjs 与 Express 服务器
【发布时间】:2022-01-21 18:42:06
【问题描述】:

我正在尝试使用 Express 服务器和 Nextjs 构建一个带有仪表板的基本登录页面。用户使用正确的凭据登录后,他们会通过身份验证,然后重定向到仪表板……或者至少应该这样。似乎在调用 Router.push("/Dashboard") 时,发出了不正确的请求。但是,如果我只是在地址栏中输入 http://localhost:3000/Dashboard 就可以了。

获取仪表板路由

server.get('/Dashboard', checkSignIn, (req, res) => {

    console.log("In dashboard")
    if(req.session.page_views){
      req.session.page_views++;
   } else {
      req.session.page_views = 1;
   }
   console.log("Page views: ", req.session.page_views)

    return handle(req, res)

  })

从客户端登录并重定向

const router = useRouter();
const attemptLogin = async (event: KeyboardEvent) => {
    const username: string = event!.target!.username!.value;
    const password: string = event!.target!.password!.value;

    fetch("http://localhost:3000/SignIn", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ username, password }),
    })
      .then((res) => {
        if (res.status === 200) {
          console.log("Status is 200");
          return router.push("/Dashboard");
        }
      })
      .catch((err) => console.log("err is", err));
  };

当我在地址栏中手动键入 http://localhost:3000/Dashboard 时,请求如下所示

这是调用 router.push 时请求的样子

希望有人可以提供帮助。谢谢。

编辑:我在重定向时在控制台中收到这些错误(和输出)

【问题讨论】:

  • 调用router.push("/Dashboard") 将触发您的自定义服务器无法处理的客户端导航。重定向时控制台中是否出现任何错误?
  • 有趣。我认为服务所有页面是服务器的工作。我已经更新了我的响应,包括重定向时控制台中打印的错误和输出。

标签: node.js typescript express next.js


【解决方案1】:

所以我发现了这个问题。这是因为我在没有调用 event.preventdefault() 的情况下提交了一个表单,我认为这是一个不正确的获取请求(因此出现上面的错误),以及重新加载页面。新的尝试登录代码(我在表单提交上调用的函数)是

const attemptLogin = async (event: KeyboardEvent) => {
    event.preventDefault();
    const username: string = event!.target!.username!.value;
    const password: string = event!.target!.password!.value;

    fetch("http://localhost:5000/SignIn", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ username, password }),
    })
      .then((res) => {
        if (res.status === 200) {
          console.log("Status is 200");
          return router.push("/Dashboard");
        }
      })
      .catch((err) => {
        console.log("err is", err);
        event!.target!.reset();
      });
  };

【讨论】:

    猜你喜欢
    • 2019-07-03
    • 2022-12-31
    • 2020-09-06
    • 2021-07-23
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    相关资源
    最近更新 更多