我有两个应用程序已链接:一个作为服务器(express)在端口5000上,另一个作为客户端(React)在端口3000上。我想从服务器向客户端发送数据--到特定页面。
流程:
1. 用户在localhost:3000上点击'登录' 2. 他们被重定向到返回代码并重定向到localhost:5000/api/callback的外部站点 3. router.get('/api/callback') 根据代码获取授权令牌然后重定向到localhost:3000/dashboard(通过React Router显示Dashboard组件) 4. 仪表板通过从服务器抓取Token来将其保存在其状态中 5. 然后,仪表板将调用服务器以根据Token获取其他数据
我意识到这很复杂,但基本上这就是我的问题所在; 我不完全明白如何使Express和React正确通信。
在server.js中:
流程:
1. 用户在localhost:3000上点击'登录' 2. 他们被重定向到返回代码并重定向到localhost:5000/api/callback的外部站点 3. router.get('/api/callback') 根据代码获取授权令牌然后重定向到localhost:3000/dashboard(通过React Router显示Dashboard组件) 4. 仪表板通过从服务器抓取Token来将其保存在其状态中 5. 然后,仪表板将调用服务器以根据Token获取其他数据
我意识到这很复杂,但基本上这就是我的问题所在; 我不完全明白如何使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
,然后传递必要的数据?
window.history.replaceState
来去掉它。这是被认为是一种hack还是正常行为(或者哈希通常只是被忽略了)? - idlackage