idl*_*age 4 node.js express reactjs react-router
我有两个链接的应用程序:一个在端口 5000 上充当服务器(express),另一个在端口 3000 上充当客户端(React)。我想将数据从服务器发送到客户端 - 到特定页面.
流动:
localhost:3000localhost:5000/api/callbackrouter.get('/api/callback')根据代码获取授权令牌,然后重定向到localhost:3000/dashboard(通过 React Router 显示仪表板组件的位置)我意识到这很复杂,但这基本上是我遇到麻烦的地方;我不完全了解如何让 Express 和 React 正确通信。
在 server.js 中:
router.get('/callback', async (req, res) => {
const code = req.query.code;
const token = await getAuthorizationTokenFromExternalSite(code);
// Poor attempt to persist data
res.cookie('token', token);
// Poor attempt to let the user see this URL
res.redirect("http://localhost:3000/dashboard");
});
router.get('/dashboard', (req, res) => {
res.send({ token: req.cookies['token'] });
});
Run Code Online (Sandbox Code Playgroud)
客户端/src/App.js
class App extends Component {
render() {
return(
<BrowserRouter>
<div>
<Route exact path="/" component={LoginPage} />
<Route path="/dashboard" component={Dashboard} />
</div>
</BrowserRouter>
);
}
}
export default App;
Run Code Online (Sandbox Code Playgroud)
客户端/src/Dashboard.js
class Dashboard extends Component {
state = { token: null };
componentDidMount() {
fetch('/api/dashboard')
.then(res => this.setState({ token: res.token }));
}
render() {
return(
<div>
Tis the Dashboard, the token is {this.state.token}.
</div>
);
}
}
export default Dashboard;
Run Code Online (Sandbox Code Playgroud)
将用户localhost:3000从服务器带回,然后传递必要数据的正确方法是什么?
我认为将此令牌放在#<token here>将用户重定向到 UI 的 uri 位中的哈希中是很常见 的。#uri的片段不会发送到您重定向到的后端服务器,因此比将其放在后面要好一些?。然后您可以(在 ui 中)解析令牌并使用它来发出请求。通常通过传递 http 标头Authorization: Bearer ${token}。
如果仅使用 http(这意味着 UI 无法以编程方式访问它),并且后端知道查看 cookie 以获取令牌,则将其放入 cookie 中就可以了。从长远来看,这比仅通过 URL 将访问令牌传递给 UI 更复杂(在我看来)。
审查身份验证的流程/动态;万一它被证明是有帮助的:
如果您有多个提供商可以合作,则选项 2 会更容易;例如 facebook & google & dropbox,并且您有一个服务器来管理令牌。这是更经典的做事方式。
选项 1 是无服务器的,只需重定向回您的应用程序并让 UI 执行任何必要的身份验证流程,管理 UI 代码中的令牌和事物。
| 归档时间: |
|
| 查看次数: |
3747 次 |
| 最近记录: |