首页 > 解决方案 > ExpressJS:重定向到客户端处理的 URL

问题描述

我将 ExpressJs 用于后端,将 ReactJS 用于前端。服务器在 localhost:3000 上运行,客户端在 localhost:8080 上运行。我想在用户成功登录后将用户重定向到聊天页面。所以我在服务器中有代码:

(req, res) => {
  //doing some authenticate actions up here
  if (/*successful*/) {
    //some actions here
    res.redirect("/chat");
  }

  //actions on failure down here
};

但是登录帐户后,我收到此错误

GET http://localhost:8080/chat 404 (Not Found)

http://localhost:8080/chat是存在的,它是由客户端处理的,如果我在地址栏中输入它然后去,我仍然可以访问聊天页面。

我还有处理任何与服务器路由不匹配的请求的代码,以便可以将请求发送到客户端进行处理:

app.get("*", (req, res) => {
    res.sendFile(path.join(__dirname, "client/dist/index.html"));
});

我的代码有什么问题?我错过了什么?

标签: javascriptnode.jsreactjsexpress

解决方案


您应该在 API 成功响应后重定向用户。后端不能更好地处理它,因为您有一个单页应用程序,从技术上讲,它没有服务器知道的其他页面,这就是为什么您在尝试重定向到http://localhost:8080/chat. 它只知道为index.html您的捆绑包提供反应代码的文件。您能够在/chat地址栏中输入的原因是您的 UI 设置为处理来自您正在使用的路由器的请求。它不是将您引导到那里的服务器。

应该很简单,举个例子:

logUserIn = async (userData) => {
  const isAuthed = await authenticateUser(userData)
  if (isAuthed) {
    this.props.history.push('/chat');
  } else {
    console.log('User not found!');
  }
}

推荐阅读