如何从express重定向到react-router? [英] How do I redirect into react-router from express?
问题描述
我正在将身份验证添加到我的应用程序中,该应用程序使用 react-router.我在 auth-flow react-router 中的示例,但使用护照而不是示例使用的本地存储.这一切正常.
I'm adding authentication into my app, which uses react-router. I've patterned the client routing after the auth-flow example in react-router, but using passport instead of the localstorage that the example uses. this all works fine.
下一步是保护我在 server.js
中为 express 定义的路由.我可以将重定向发送到 /#/login
,但这感觉很脆弱.在服务器端将 URL 导出到 react-router 提供的登录路由的最佳方法是什么?
The next step is protecting routes I am defining for express in server.js
. I could send a redirect to /#/login
, but this feels brittle. What's the best way to derive a URL on the server side to a login route served by react-router?
这是我现在在 server.js
中的内容,它可以工作,但感觉很脆弱:
Here's what I have now in my server.js
, which works, but feels brittle:
app.get('/protected',
// redirecting to #/login seems bad: what if we change hashhistory, etc.
passport.authenticate('local', { failureRedirect: '/#/login'}),
function(req, res) {
res.render('whatever');
});
推荐答案
在 express 上配置路由以获取所有路由并使用 react-router 路由,这样,ejem.(希望能帮到你)
Config route on express to get all routes and routing with react-router, in this way, ejem. (I hope this can help you)
server.js
import express from 'express'
import path from 'path'
const app = express();
app.use(express.static(__dirname + '/public'));
app.get('*', (req,res) => res.sendFile(path.join(__dirname+'/public/index.html'))).listen(3000,() => console.log('Server on port 3000'))
routes.jsx
import React from 'react'
import ReactDOM from 'react-dom'
import { Router, Route, Link, browserHistory, IndexRedirect } from 'react-router'
import App from '../views/app.jsx'
const Routes = React.createClass({
render(){
return(
<Router history={ browserHistory }>
<Route path="/" component={App}>
<IndexRedirect to="/dashboard"/>
<Route path="dashboard" name="Dashboard" component={App} />
<Route path="pages" name="Pages" component={Pages} />
<Route path="/:Id" component={Page}/>
<Route path="/:Id/inbox" name=':ids' component={Inbox}/>
</Route>
<Route path="*" component={App}>
<IndexRedirect to="/dashboard" />
</Route>
</Router>
);
}
});
ReactDOM.render(<Routes />, document.getElementById('app'))
这篇关于如何从express重定向到react-router?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!