私は主にバックエンドを行っているので、JavaScriptだけではありませんが、設計している管理パネルに問題があります。サイトの一部には、特定のユーザーのみがアクセスできます。
保護されたコンポーネントがロードするたびに、私はリターンが200または403は、200応答が呼ばれるキーが含まどちらか戻って私のRESTサーバにリクエストを送信しredirect
ています、False
。だから私の考えは次のことをすることでした:
...
import { Redirect } from 'react-router-dom';
import axios from 'axios';
class MyProtectedComponent extends Component {
constructor(props) {
super(props);
this.state = {
authCalled: false,
redirect: true,
};
}
componentDidMount() {
console.log("mounting...")
axios.get('<https://url>',
{headers: {"Authorization": localStorage.getItem("token")}})
.then(res => {
this.setState({
redirect: res.data.data.redirect,
authCalled: true,
});
})
}
render() {
if (this.state.authCalled === false) {
return (
<div className="animated fadeIn">
<Row>
<Col>
authenticating...
</Col>
</Row>
</div>
)
}
if (this.state.redirect === true) {
return <Redirect to={{pathname: "/nonauthpage"}} />;
}
return ( ....... <main code> ..... )
これで、サーバーがユーザーにアクセスを許可するために200を送り返すと、コンポーネントがロードされますが、そうでない場合、ページは<authenticating>
フェーズでスタックし、決してRedirect
sになりません。
私のJavaScriptはすべて独学です。私がやっていることは、この種のことを実行するのに悪い習慣である場合は、それを適切に行う方法を教えてください。または、なぜこれが機能しないのかを教えてください。
axiosを使用しています。つまり、応答が200(または2XX)でない場合、はthen
実行されず、代わりに次のようにチェーン実行する必要があり.catch
ます。
componentDidMount() {
console.log("mounting...")
axios.get('<https://url>',
{headers: {"Authorization": localStorage.getItem("token")}})
.then(res => {
this.setState({
redirect: res.data.data.redirect,
authCalled: true,
});
}).catch(error => {
// You can do additional checks here like e.g. check if the response code is 403 or 401
this.setState({
redirect: true,
authCalled: true
});
})
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加