我在我的react应用程序中定义了路由器。我的申请表有3页。用户成功登录后,将进入下一个屏幕。流量很好。但有一个问题。当我直接在我的应用程序中输入其他页面的URL时,无论用户是否登录,它都会加载该页面。我想补充一下这个。如果用户未登录,则必须将其重定向到登录页面。
这些是我的路线
<Route path="/" component={LoginPage}/>
<Route path='app' component={App}>
<IndexRoute component={Home}/>
<Route path='/video-screen' component={VideoScreen}>
<IndexRoute component={TagList}/>
<Route path='/add' component={AddTags}/>
<Route path='/TagList' component={TagList}/>
<Redirect from='*' to='/'/>
</Route>
</Route>
</Router>
这是我的登录组件的方法,它检查登录凭据并在登录成功时将用户带到下一页
handleLoginButtonClick() {
var that = this;
let token;
var settings = {
"async": true,
"crossDomain": true,
"url": "https://www.backend.example.raccte.com/auth/login/",
"method": "POST",
"credentials": 'include',
"headers": {
"content-type": "application/x-www-form-urlencoded",
},
"data": {
"password": document.getElementById("password").value,
"username": document.getElementById("username").value
},
success:( response, textStatus, jQxhr )=> {
this.props.tokenAction(response.auth_token);
}
}
$.ajax(settings).done((response) => {
token = response.auth_token
console.log(token);
this.context.router.push('/app')
});
更新
function authorize(){
if(window.localStorage.token == null){
browserHistory.push('/')
}
}
function getRoutes(store) {
return (
<Router>
<Route path="/" component={LoginPage}/>
<Route path='app' component={App} onEnter={this.authorize}>
<IndexRoute component={Home}/>
<Route path='/video-screen' component={VideoScreen}>
<IndexRoute component={TagList}/>
<Route path='/add' component={AddTags}/>
<Route path='/TagList' component={TagList}/>
<Redirect from='*' to='/'/>
</Route>
</Route>
</Router>
)
}
export default getRoutes;
给我一个错误,说明Uncaught ReferenceError:authorize未定义
答案 0 :(得分:1)
路由具有可用于此的onEnter功能。假设您有一个函数在包含React路由器内容的组件内对其进行授权。你可以这样做(这里有一些伪代码):
authorize() {
if (user is NOT authorized) browserHistory.push(login page)
}
<Route path="/" component={LoginPage}/>
<Route path='app' component={App} onEnter={this.authorize}/>
</Router>
这样即使他们直接将URL输入浏览器URL栏,仍然会调用onEnter函数,如果他们没有登录,它会将它们重定向到登录页面。
答案 1 :(得分:1)
问题是你在<?php
namespace AppBundle\Twig\Extension;
// ...
class MyExtension extends \Twig_Extension
{
// ...
public function getFunctions()
{
return [
new \Twig_SimpleFunction('current_locale', [$this, 'currentLocale']),
new \Twig_SimpleFunction('current_uri', [$this, 'currentUri']),
];
}
public function currentLocale()
{
return $this->get('request_stack')->getMasterRequest()->getLocale();
}
public function currentUri()
{
return $this->get('request_stack')->getMasterRequest()->getUri();
}
public function getName()
{
return 'my';
}
}
组件中声明了authorize
方法,你需要在你定义所有App
的文件中声明它,如下所示:
routes
答案 2 :(得分:1)
我使用高阶组件来检查此示例
<强> RequireAuth 强>
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
export default function (ComposedCmponent) {
class RequireAuth extends Component {
componentWillMount () {
//we need to check if user is authenticated before the component will mount
//here i check if the user is authenticated i'm using JWT authentification for this exemple, usually i use local storage to save the token and we can check the validation of the token
//If the user is not authenticated we redirect to /login
let validtoken = window.localStorage.getItem('id_token')
if (!this.props.isAuthenticated || !validtoken) {
this.context.router.push('/login')
}
}
componentWillUpdate (nexProps) {
// we need to the same as we did in componentWillMount
// in case component will update the use not authenticated
//If the user is not authenticated we redirect to /login
if (this.props.isAuthenticated !== nexProps.isAuthenticated) {
if (!nexProps.isAuthenticated) {
this.context.router.push('/login')
}
}
}
render () {
//now the user is authenticated we render the component passed by HOC component
return (
<ComposedCmponent {...this.props} />
)
}
}
如果我想要安全路径,我在路由器中使用HOC RequireAuth
<Route path='/' component={App}>
<Route path='/dashboard' component={requireAuth(Dashboard)} />
</Route>