node.js – 如何从express重定向到react-router?

我正在为我的应用程序添加身份验证,它使用react-router.我已经在反应路由器中的
auth-flow示例之后构建了客户端路由,但是使用了护照而不是示例使用的本地存储.一切正常.

下一步是保护我在server.js中为express定义的路由.我可以发送重定向到/#/ login,但这感觉很脆弱.将服务器端的URL派生到react-router服务的登录路由的最佳方法是什么?

这是我现在在我的server.js中所拥有的,它有效,但感觉很脆弱:

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.

(我希望这可以帮到你)

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'))
点赞