Javascript 从后端强制登录Resact after 401
我想使用以下流程进行反应:Javascript 从后端强制登录Resact after 401,javascript,reactjs,Javascript,Reactjs,我想使用以下流程进行反应: 用户正在做某事 用户尝试打开需要身份验证的页面 前端向服务器发送请求(即获取某些对象的列表) 若用户已通过身份验证,服务器将用对象列表响应,状态将更新,并且每个人都很高兴 若用户未经身份验证,服务器响应401 unauthorized,我想显示登录表单(第页),执行登录并重定向到最初请求的页面 我现在拥有的是: App.js: class App extends Component { render() { return ( <Bro
- 用户正在做某事
- 用户尝试打开需要身份验证的页面
- 前端向服务器发送请求(即获取某些对象的列表)
- 若用户已通过身份验证,服务器将用对象列表响应,状态将更新,并且每个人都很高兴
- 若用户未经身份验证,服务器响应401 unauthorized,我想显示登录表单(第页),执行登录并重定向到最初请求的页面
class App extends Component {
render() {
return (
<BrowserRouter>
<Switch>
<Route exact path="/login" name="Login Page" component={Login} />
<Route path="/private" name="Private page" component={PrivatePage}/>
<Route path="/" name="Home" component={Index} />
</Switch>
</BrowserRouter>
);
}
}
这当然是代码的简化版本-但显示了我的意图。您必须检查从请求返回的状态代码,然后,如果状态为401,您应该使用react router重定向到登录页面
这里有一个我建议将需要保护的路由组件包装到一些自定义的ProtectedRoute组件中,这些组件将访问redux状态,或者获得一些isAuthenticated道具,然后渲染路由
然后在api调用中接收到401后,只需更改isAuthenticated in state,或redux state,或存储它的任何位置。我认为有两种方法 从后端重定向。或者通过react路由器在前端重定向(因为您使用的是react路由器) 在前端使用react路由器:
getProfile(){
return fetch('http://some_endpoint.com', {
method: 'GET',
body: '{}'
})
.then(/* probably something here needs to redirect to Login page in case of 401? */)
.catch((err)=>{
// you should get unauthorized.
this.setState({redirecting: true}) // this state is set which will render a react component called Redirect from react router
})
}
然后在渲染中(注意:需要导入此内容)
这实际上是我想要避免的事情——在我看来,保持用户身份验证的全局状态不是一个好主意opinion@mrbox为什么不呢,出于兴趣?这似乎是应用程序的各个部分都想知道的。如果你刷新页面,商店会被清理,因此你需要重新登录。谢谢-但这意味着我需要使Api类成为使用setState的组件?正如您所看到的,Api只是一个类——所以在我看来,它必须修改一些全局状态,否则我必须在每个组件中放置重定向逻辑,对吗?实际上,我想在前端使用react路由器,而不是后端重定向。
export class Api {
getProfile(){
return fetch('http://some_endpoint.com', {
method: 'GET',
body: '{}'
})
.then(/* probably something here needs to redirect to Login page in case of 401? */)
}
}
let api = new Api();
export default api;
getProfile(){
return fetch('http://some_endpoint.com', {
method: 'GET',
body: '{}'
})
.then(/* probably something here needs to redirect to Login page in case of 401? */)
.catch((err)=>{
// you should get unauthorized.
this.setState({redirecting: true}) // this state is set which will render a react component called Redirect from react router
})
}
render() {
return (
if(redirecting){
<Redirect to="/login">
}
// other stuff
)
}
app.post(
'/api/login',
passport.authenticate('local', {
// successRedirect: '/profile',
// failureRedirect: '/error'
}),
(req, res) => {
res.send('authenticated!')
}
)