【发布时间】:2018-02-28 03:19:42
【问题描述】:
我正在尝试验证私有路由。我通过在允许访问之前检查 cookie 来使其工作。但是,cookie 可以被欺骗,所以我有一个 API 端点,它接受 cookie 并返回其是否有效。
没有 API 的工作版本:
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
cookies.get('sessionid') ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/',
state: { from: props.location }
}}/>
)
)}/>
)
ReactDOM.render((
<Router>
<Switch>
<Route exact path="/" component={Login}/>
<PrivateRoute exact path="/home" component={Home} />
<PrivateRoute exact path="/upload" component={Upload}/>
<PrivateRoute exact path="/logout" component={Logout}/>
<PrivateRoute exact path="/review" component={Review}/>
<Route component={ NotFound } />
</Switch>
</Router>
), document.getElementById('root'))
API 调用的附加代码:
axios.post(process.env.REACT_APP_API_URL+'/account/validate-session', {
t1_session_id: cookies.get('sessionid')
})
.then(function (response) {
if(response.data.status === "OK"){
console.log('authenticated go to private route');
} else {
console.log('not valid, redirect to index');
}
}.bind(this))
.catch(function (error) {
console.log('not valid, redirect to index');
}.bind(this));
问题是我不确定如何将代码的 API 部分合并到主路由部分。
谢谢
【问题讨论】:
标签: reactjs cookies react-native react-router