1
特定のパスにアクセスする前にユーザーが存在することを確認します。React Router:認証フローが機能しない
私は、ユーザーを取得する機能を持っており、認証を必要とするもの:私は私のコンソールログがある見ることができ、私はその後、必要機能を適用
フォーカス取得時<Route path="/modules" component={ModulesData} onEnter={requireAuth} />
function getUser() {
$.ajax({
url: '/getUser',
method: 'GET'
}).done(data => {
if(data.user == "no user"){
console.log('permission denied');
alert('you must be logged in to access this page.')
return null
} else {
console.log('permission granted');
return true
}
});
}
function requireAuth(nextState, replace) {
if (!getUser()) {
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname }
});
}
}
正しいかどうかに基づいてユーザーがログインしているかどうかにかかわらず、ユーザーのステータスに関係なく、常にログインページに戻されます。
import React from 'react';
import { render } from 'react-dom';
import { Router, Route, browserHistory, IndexRoute, Redirect } from 'react-router';
import App from './App';
require('./stylesheets/main.scss');
function getUser() {
$.ajax({
url: '/getUser',
method: 'GET'
}).done(data => {
if(data.user == "no user"){
console.log('permission denied');
alert('you must be logged in to access this page.')
return null
} else {
console.log('permission granted');
return true
}
});
}
function requireAuth(nextState, replace) {
if (!getUser()) {
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname }
});
}
}
render((
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="/modules" component={ModulesData} onEnter={requireAuth} />
</Route>
</Router>
), document.getElementById('app'));
私はReact Router - Auth Flowの例(https://github.com/reactjs/react-router/blob/master/examples/auth-flow/app.js)のようにしていました。 I.E .: 多くのルートを保護する必要があるため、実際のコンポーネント内で実行する必要がありますが、理想的ではありません。ルートのパス= "ダッシュボード"コンポーネント= {ダッシュボード} onEnter = {必須} /> – fresh5447