javascript - 登录前检查用户有效性
问题描述
用户登录应用程序时出现意外行为。我将 jwt 令牌存储在 cookie 中。在登录应用程序之前,我检查了 jwt 令牌是否存在以及该令牌在后端是否有效。
下面是我的代码。这是 app.js。
class App extends Component {
render() {
return (
<BrowserRouter>
<Layout>
<LoginRoute></LoginRoute>
</Layout>
</BrowserRouter>
);
}
}
LoginRoute 组件如下。
const LoginRoute = withRouter(({ history }) => (
isValidUser() ? (
<Switch>
<Route path="/incident-reporting" component={Home}></Route>
<Redirect path='/' to='/incident-reporting/home' />
<NotFound />
</Switch>
) : (
<Switch>
<Route path="/" exact component={Login}></Route>
<NotFound></NotFound>
</Switch>
)
))
这是 isValidUser()
const isValidUser = () => {
if (cookies.get("token")) {
let token = cookies.get("token")
axios.get("https://0.0.0.0:9094/auth/v1.0.0/user-info", {
headers: { 'Authorization': 'Bearer ' + token }
}).then(
response => {
return true;
}
).catch(
error => {
return false;
}
)
//return true
} else {
return false;
}
}
但我无法使用有效令牌登录应用程序。在执行 axios 发布请求之前isValidUser()
返回。undefined
如何解决这个问题呢?
解决方案
您需要等待 isValidUser 完成。为此,您可以这样做:
const LoginRoute = withRouter(async ({ history }) => (
let isUserValid = await isValidUser()
isUserValid ? (
<Switch>
<Route path="/incident-reporting" component={Home}></Route>
<Redirect path='/' to='/incident-reporting/home' />
<NotFound />
</Switch>
) : (
<Switch>
<Route path="/" exact component={Login}></Route>
<NotFound></NotFound>
</Switch>
)
))
在 isValidUser 上:
const isValidUser = () => {
if (cookies.get("token")) {
let token = cookies.get("token")
return axios.get("https://0.0.0.0:9094/auth/v1.0.0/user-info", {
headers: { 'Authorization': 'Bearer ' + token }
}).then(
response => {
return true;
}
).catch(
error => {
return false;
}
)
//return true
} else {
return false;
}
}
推荐阅读
- android - Kotlin 列表自行修改
- android - 带有 OpenCV 错误 dlopen 的 Android Studio 失败:找不到库“libopencv_java3415.so”
- firebase - 将表日历连接到 Firebase Flutter
- json - Json 数组上的 Laravel 关系
- python - 如何在 PYTHON 中从当月(EOMONTH 的 excel 版本)中找到当月的最后一天?
- swift - 连接到 SocketIO 时 Swift 中的长轮询请求错误
- firebase - Firebae 通知主题限制
- python - python中...(三个点)的含义是什么
- javascript - 反应计算器太多渲染
- sql - BigQueryInsertJobOperator 无法通过 Airflow 插入 1 亿行