gpt4 book ai didi

javascript - 从后端强制登录 401 后使用react

转载 作者:搜寻专家 更新时间:2023-11-01 04:12:45 26 4
gpt4 key购买 nike

我想使用以下流程使用react:

  • 用户正在做某事
  • 用户尝试打开需要身份验证的页面
  • 前端向服务器发送请求(即获取一些对象的列表)
  • 如果用户通过身份验证,服务器会响应对象列表,状态会更新,大家都很高兴
  • 如果用户未通过身份验证服务器响应 401 unauthorized,我想显示登录表单(页面),执行登录并重定向到最初请求的页面

我现在拥有的是:

应用程序.js:

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>
);
}
}

PrivatePage.js:

import api from '../../api';
class PrivatePage extends Component {
state = {
first_name: '',
last_name: ''
};
componentDidMount() {
api.getProfile().then((res) => { /* this needs to be executed only if status code was 200 */
this.setState({
first_name: res.first_name,
last_name: res.last_name
})
})
}

render() {
return (
<div>
<p>first name: {this.state.first_name}</p>
<p>last name: {this.state.last_name}</p>
</div>
);
}
}

API.js:

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;

这当然是代码的简化版本 - 但表明了我的意图。

最佳答案

我建议将需要保护的 Route 组件包装在一些自定义的 ProtectedRoute 组件中,这些组件将访问 redux 状态,或者获取一些 isAuthenticated 属性,然后呈现 Route。 Protected routes .

然后在您的 api 调用中收到 401,只需更改状态中的 isAuthenticated 或 redux-state 或您存储它的任何位置。

关于javascript - 从后端强制登录 401 后使用react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50990141/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com