【发布时间】:2018-09-11 03:25:47
【问题描述】:
我有两个链接的应用程序:一个在端口 5000 上充当服务器(express),另一个在端口 3000 上充当客户端(React)。我想将数据从服务器发送到客户端--一个特定的页面。
流程:
- 用户点击
localhost:3000上的“登录” - 它们被重定向到返回代码并重定向到
localhost:5000/api/callback的外部站点 -
router.get('/api/callback')根据代码获取授权令牌,然后重定向到localhost:3000/dashboard(其中 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'] });
});
client/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;
client/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;
将用户从服务器带回localhost:3000,然后传递必要数据的正确方法是什么?
【问题讨论】:
标签: node.js reactjs express react-router