简体   繁体   English

react JS中的私有路由jsx

[英]Private Route jsx in react JS

Problem: I am trying to authenticate a user through isAuth() helpers but it is acting weird.问题:我试图通过isAuth()助手对用户进行身份验证,但它表现得很奇怪。 I want it to look for access token if any or call for access token from backend if refresh token is available, and though it works perfectly and sets access token cookie, the issue is if called from PrivateRoutes.jsx , it does not sees the tokens at all and sends the user to login page.我希望它查找访问令牌(如果有)或从后端调用访问令牌(如果刷新令牌可用),虽然它工作正常并设置访问令牌 cookie,但问题是如果从PrivateRoutes.jsx ,它看不到令牌根本并将用户发送到登录页面。

Adding required code for refs:为 refs 添加所需的代码:

isAuth():是授权():

export const isAuth = () => {
  if (window !== undefined) {
    const accessCookieChecked = getCookie("_mar_accounts_at");
    const refreshCookieChecked = getCookie("_mar_accounts_rt");
    if (accessCookieChecked) {
      return true;
    } else if (refreshCookieChecked) {
      console.log(refreshCookieChecked);
      axios({
        method: "POST",
        url: `${API_URL}/api/token`,
        data: { refresh_token: refreshCookieChecked },
      }).then((res) => {
        console.log(res);
        setCookie("_mar_accounts_at", res.data.accessToken);
        return true;
      });
    } else {
      return false;
    }
  } else {
    return false;
  }
};

PrivateRoutes.jsx PrivateRoutes.jsx

import React from "react";
import { Route, Redirect } from "react-router-dom";

import { isAuth } from "../helpers/auth";

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

export default PrivateRoute;

Can someone please see this?有人可以看看这个吗? And help!和帮助!

You are running into an async issue most likely, when you make the call in axios, the return true;您很可能遇到异步问题,当您在 axios 中进行调用时, return true; in the callback never actually returns to your funciton call in the PrivateRoute.在回调中永远不会真正返回到您在 PrivateRoute 中的函数调用。 Instead, you need to use a Promise/setState/useEffect:相反,您需要使用 Promise/setState/useEffect:

export const isAuth = () => {
  if (window === undefined) {
    return Promise.resolve(false);
  } else {
    const accessCookieChecked = getCookie("_mar_accounts_at");
    const refreshCookieChecked = getCookie("_mar_accounts_rt");
    if (accessCookieChecked) {
      return Promise.resolve(true);
    } else if (refreshCookieChecked) {
      console.log(refreshCookieChecked);
      return new Promise(resolve => {
        axios({
          method: "POST",
          url: `${API_URL}/api/token`,
          data: { refresh_token: refreshCookieChecked },
        }).then((res) => {
          console.log(res);
          setCookie("_mar_accounts_at", res.data.accessToken);
          resolve(true);
        });
      })
      
    } else {
      return Promise.resolve(false);
    }
  }
};
import React, { useState, useEffect } from 'react';
import { Route, Redirect } from 'react-router-dom';

import { isAuth } from '../helpers/auth';

const PrivateRoute = ({ component: Component, ...rest }) => {
  const [isAuthTrue, setIsAuthTrue] = useState();
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    isAuth().then(res => {
      setIsAuthTrue(res);
      setLoading(false);
    })
  })
  return (
    <>
      {loading ? (
        <div>some loading state</div>
      ) : (
        <Route
          {...rest}
          render={(props) =>
            isAuthTrue ? (
              <Component {...props} />
            ) : (
              <Redirect
                to={{ pathname: '/login', state: { from: props.location } }}
              />
            )
          }
        />
      )}
    </>
  );
};
export default PrivateRoute;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM