gpt4 book ai didi

javascript - ReactJS 身份验证不工作,重定向到登录页面失败

转载 作者:行者123 更新时间:2023-11-30 13:57:23 26 4
gpt4 key购买 nike

我在react项目中实现了私有(private)路由,但是没有找到导致认证失败的错误。重定向不起作用,调试不进入函数estaAutenticado。

token 是从 sessionStorage 中检索到的常量。

端点/usuario 从 JWT token 进行验证。

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import Routes from './servicos/Rotas';

ReactDOM.render(<Routes/>, document.getElementById('root'));

Rotas.js

import React from "react";
import { BrowserRouter, Route, Switch, Redirect } from "react-router-dom";
import { estaAutenticado } from "./Autenticacao";
import App from '../App';
import Login from '../Login';
import SelecionarFiliais from '../SelecionarFiliais';

export const rotas = [
{
path: "/login",
name: "Login",
icon: null,
component: Login,
private: false,
exact: false
},
{
path: "/selecionar_filiais",
name: "Login",
icon: null,
component: SelecionarFiliais,
private: true,
exact: false
},
{
path: "/",
name: "Dashboard",
icon: null,
component: App,
private: true,
exact: true
}
];

const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest} render={props =>
estaAutenticado() ? (
<Component {...props} />
) : (
<Redirect to={{ pathname: "/login", state: { from: props.location } }} />
)
}
/>
);

const Routes = () => (
<BrowserRouter>
<Switch>
{rotas.map((e) => (
e.private ? <Route key={e.path} exact={e.exact} path={e.path} component={e.component}/> : <PrivateRoute key={e.path} exact={e.exact} path={e.path} component={e.component}/>
))}
</Switch>
</BrowserRouter>
);

export default Routes;

函数 estaAutenticado()

export const estaAutenticado = async () => {
let result = false
if (token !== null){
result = await API.post('/usuario')
.then(function(response) {
return true
})
.catch(function(error){
return false
});
return result
}
return result
};

任何帮助,请!谢谢

最佳答案

result = await API.post('/usuario')
.then(function(response) {
return true
})
.catch(function(error){
return false
});
return result

应该是

try {
result = await API.post('/usuario')
return result
} catch(e) {
return false
}

编辑:

如果函数被反转,还有你的映射:

{rotas.map((e) => (
e.private ? <Route key={e.path} exact={e.exact} path={e.path} component={e.component}/> : <PrivateRoute key={e.path} exact={e.exact} path={e.path} component={e.component}/>
))}

应该是

{rotas.map((e) => (
!e.private ? <Route key={e.path} exact={e.exact} path={e.path} component={e.component}/> : <PrivateRoute key={e.path} exact={e.exact} path={e.path} component={e.component}/>
))}

如果它是私有(private)的,那么渲染 PrivateRoute。

关于javascript - ReactJS 身份验证不工作,重定向到登录页面失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56991054/

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