使用身份验证反应 js 重定向

时间:2021-05-13 19:09:45

标签: javascript reactjs

我是 Reactjs 的新手,如果用户登录与否,我看到了一些关于重定向/身份验证路由的问题。

我正在尝试创建一个身份验证文件,用于检查收到的令牌是否匹配并根据该结果返回 truefalse

我能够执行该函数,但在 routes.js 文件中,即使我使用 async/await,我也会收到一个未决的承诺。我希望 IsAuthenticated 返回 true 或 false。

console

auth.js:


const auth = {

    isAuth: false,
    authing: (async () => {
            
        const token = localStorage.getItem('token');
    
        await axios.post('http://localhost/api/login/auth.php', { "token": token }).then(res => {
    
            console.log(res.data);
                
            if (res.data === "authorized") {
                
                auth.isAuth = true; 
            }
    
        }).catch(err => {
            console.log(err);
            alert('Access denied');
        });
        console.log(auth.isAuth)
        return auth.isAuth;
    })()
}

export const IsAuthenticated = () => auth.authing;

routes.js:

import { IsAuthenticated } from './auth';

console.log(IsAuthenticated()); // console.log a promise

export default function Routes() {
    
    const PrivateRoute = ({ component: Component, ...rest }) => {
        return (
            <Route
                {...rest}
                render={props =>
                    IsAuthenticated() ? (
                        <Component {...props} />
                    ) : (
                        <Redirect to={{ pathname: "/", state: { from: props.location } }} />
                    )
                }
            />
        )
    }

    return (
        <BrowserRouter>
            <Switch>
                <Route path="/" exact component={Login} />
                <PrivateRoute path="/Home" component={Home} />
            </Switch>
        </BrowserRouter>
    );
}

我的代码有什么问题?

2 个答案:

答案 0 :(得分:0)

好的,我相信当您导出为“() =>”时,这已经称为 auth.authing

当您使用 IsAuthenticated() 调用 console.log 时,根据记录,这已经完成。

我会尝试尝试仅控制台“IsAuthenticated”或导出“auth.authing”然后登录“IsAuthenticated()”


编辑: 将 quokka 用于快速游乐场,我发现您确实在返回一个承诺...... auth.authing 本身就是一个承诺。

基本上,解决方案是“等待 IsAuthenticated()”

代码如下:

const auth = {

  isAuth: false,
  authing: (async () => {

    await Promise.resolve({data:"authorized"}).then(res => {

      console.log(res.data);

      if (res.data === "authorized") {

        auth.isAuth = true;
      }

    }).catch(err => {
      console.log(err);
      console.log('Access denied');
    });
    console.log(auth.isAuth);
    return auth.isAuth;
  })()
};

const IsAuthenticated = () => auth.authing;

console.log(await IsAuthenticated())

答案 1 :(得分:0)

const auth =  async()=>{
        try { // simplify code with trycatch
            const {data} = await axios.post('http://localhost/api/login/auth.php', { "token": token })
            if (data === "authorized") {
             // we know him
             return true;
            }else{
             // stranger alert!!
             return false;

            }
            
        } catch (error) {
            alert('Something went wrong');
            console.log(error);
            return false;  
        }
    }


exports const IsAuthenticated = auth(); 

看来您做得太多了,请从您的 auth() 函数返回 true 或 false。像这样然后保存为变量“IsAuthenticated”以在您的情况下不带括号使用

export default function Routes() {

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

return (
    <BrowserRouter>
        <Switch>
            <Route path="/" exact component={Login} />
            <PrivateRoute path="/Home" component={Home} />
        </Switch>
    </BrowserRouter>
);
}