gpt4 book ai didi

javascript - 如何处理客户端 React 应用程序的外部重定向?

转载 作者:行者123 更新时间:2023-12-04 15:38:58 24 4
gpt4 key购买 nike

我正在构建一个使用 True Layer 开放式银行 API 的网络应用程序。该应用程序有一个使用 React 路由器的 React 前端和一个 Express 和 Nodejs 后端。目前我正在使用 react build 脚本来提供静态文件:

const app = express();

app.use(cors());
app.use(express.json());

app.use(express.static('../client/build'));
app.get('*', (req, res) => {
res.sendFile('index.html', {root: path.join(__dirname, '../client/build/')});
});

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log("Server listening on port: ", PORT);
});

// The API routes are imported below

此解决方案运行良好,但当用户被重定向到 True Layer 的身份验证页面时,会生成一个 OAuth 代码并将其作为 url 查询传递回客户端上的路由。问题是,当 True Layer 将用户重定向回我的应用程序时,url 由服务器解释,而不是 react 路由器/浏览器,因此它返回 cannot GET/myAccounts。我研究过使用像 Next.js 这样的库为 React 客户端使用服务器端渲染,但我想知道是否有一种方法可以做到这一点而不必显着重构我的代码。

我的 React 路由器设置:

class App extends Component {
render() {
return (
<Router>
<Route name="Landing" path="/" exact component={Login} />
<Route name="Login" path="/login" exact component={Login} />
<Route name="MyAccounts" path="/myAccounts" exact component={Home} />
</Router>
);
}
}

/myAccounts 路由呈现 Home 组件/页面,其中提取了 code 参数:qs.parse(props. location.search)['?code'],并发送到我的服务器以完成 OAuth 过程。

如有任何帮助,我们将不胜感激。

最佳答案

The issue is that when True Layer redirect the user back to my app the url is interpreted by the server and not the react router/browser so it returns cannot GET /myAccounts

发生的事情是:
路径 /myAccounts 是 React SPA 的内部路径,它显示由 MyAccounts 组件呈现的内部 SPA 页面。网络服务器不知道此页面并返回“无法获取/myAccounts”。此网络服务器行为不正确不是因为网络服务器不支持 True Layer/OAuth,而是因为网络服务器没有正确支持 SPA。

应该发生什么:
网络服务器应该通过实现回退行为来支持 SPA,这只是意味着服务器将对未知页面的请求重定向到 SPA 登录页面。例如,使用 historyApiFallback 在 webpack-dev-server 中启用此行为它专门用于支持 SPA。

任何 SPA 都需要回退行为,因为用户可以在导航栏中看到任何内部页面的路径,并且可以手动重新键入并按 Enter 或刷新浏览器。在这两种情况下,网络服务器都收到了对它不知道的内部 SPA 页面的请求,并且以 404 错误响应对用户来说看起来不太好。

在 Express 中实现后备后,您可以将一段数据添加到被重定向到着陆页的请求中。这样您的 Landing 组件就会看到这个可选部分并在内部(网络服务器不知道)重定向到 MyAccounts 组件。

关于javascript - 如何处理客户端 React 应用程序的外部重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58701717/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com