javascript - 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"));
});
我的代码有什么问题?我错过了什么?
解决方案
您应该在 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!');
}
}
推荐阅读
- javascript - 在线显示 Word 文档
- javascript - 左上角的 SVG 动画模式
- css - 如何缩小 NuxtJs 中的内部 css?
- amazon-web-services - AWS Lambda /tmp python脚本导入模块错误
- javascript - 将数组从ajax调用传递给控制器,控制器中的数组为空
- android - 是否可以使用 AndroidX 导航将片段中的操作栏标题居中?
- ld - AArch64 - GNU ld - 多个链接器脚本(用于内核和用户空间)
- automapper - AutoMapper.Collection - 如果源集合属性为空,则完全跳过映射
- c++ - 空默认构造函数与隐式定义的不同机器代码
- elasticsearch - 为 elasticsearch 客户端设置 Kubernetes 就绪状态