Reactjs 如何通过更改url阻止用户访问网页

Reactjs 如何通过更改url阻止用户访问网页,reactjs,authentication,react-redux,Reactjs,Authentication,React Redux,使用已经创建的api,当用户进入登录页面时,他们可以选择登录,或者只编辑localhost 3000 to/dashboard的url,而不会重定向回登录页面。只有在提供用户名和密码时,用户才可以访问它。尝试多次更改代码,甚至更改了privateroutes,但似乎仍然无法使其不允许您访问该页面。重新启动之前的代码,试图找出它,即使我肯定我在看答案 它混合了Login.js和privaterout.js import axiosWithAuth from '../data/axiosWithAu

使用已经创建的api,当用户进入登录页面时,他们可以选择登录,或者只编辑localhost 3000 to/dashboard的url,而不会重定向回登录页面。只有在提供用户名和密码时,用户才可以访问它。尝试多次更改代码,甚至更改了privateroutes,但似乎仍然无法使其不允许您访问该页面。重新启动之前的代码,试图找出它,即使我肯定我在看答案

它混合了Login.js和privaterout.js

import axiosWithAuth from '../data/axiosWithAuth';
const Login = props => {


const [loginCreds, setLoginCreds] = useState({
    username: "",
    password: "",
    err: null
  });

  const handleChange = e => {

    setLoginCreds({

      ...loginCreds,
      [e.target.name]: e.target.value,
      err: null
    });
  };

  const login = () => {
    const proxy = "https://cors-anywhere.herokuapp.com/";
    const url = "https://pintreachbackend.herokuapp.com/api/auth/login";
    axiosWithAuth()
      .post(proxy +url , {
        username: loginCreds.username,
        password: loginCreds.password
      })
      .then(res => {
        localStorage.setItem("token", res.data.token);
        props.history.push("/dashboard");
        console.log(login)
      })
      .catch(err =>
        setLoginCreds({
          ...loginCreds,
          err: "Error logging in. Please try again."
        })
      );
  };

  const handleSubmit = e => {
    e.preventDefault();
    loginCreds.username === "" || loginCreds.password === ""
      ? setLoginCreds({
          ...loginCreds,
          err: "Please complete all login fields."
        })
      : login();
  };
  return (
    <div className="login-page">
    <form>
        <h4>Enter Login Creds</h4>
        <input
          type="text"
          name="username"
          placeholder="Enter username..."
          value={loginCreds.username}
          onChange={handleChange}
          autoComplete="username"
        />
        <input
          type="password"
          name="password"
          placeholder="Enter password..."
          value={loginCreds.password}
          onChange={handleChange}
          autoComplete="current-password"
        />
        <button onClick={handleSubmit}>Login</button>
        {loginCreds.err && (
          <div className="error-container">{loginCreds.err}</div>
        )}
      </form>
    </div>
  );
};
export default Login;  ~~~    










This is the PrivateRoute.js

    ~~~import React from "react";
    import { Route, Redirect } from "react-router-dom";
    import axiosWithAuth from "../data/axiosWithAuth";

    /*
    Private Route rules:
    1. It has the same API as <Route />.
    2. It renders a <Route /> and passes all the props through to it.
    3. It checks if the user is authenticated, if they are, it renders the 
    “component” prop. If not, it redirects the user to /login.
    */
    const PrivateRoute = ({ component: Component, ...rest }) => {
    // const Component = props.component

    return (
    <Route
      {...rest}
      render={props =>
        axiosWithAuth ? (
          <Component {...props} />
        ) : (
          <Redirect to={{ pathname: '/login', state: { from: props.location } 
    }} 
    />
        )
       }
      />
     )
    }

    export default PrivateRoute
从“../data/axiosWithAuth”导入axiosWithAuth;
const Login=props=>{
const[loginCreds,setLoginCreds]=useState({
用户名:“”,
密码:“”,
错误:空
});
常量handleChange=e=>{
setLoginCreds({
…loginCreds,
[e.target.name]:e.target.value,
错误:空
});
};
常量登录=()=>{
常量代理=”https://cors-anywhere.herokuapp.com/";
常量url=”https://pintreachbackend.herokuapp.com/api/auth/login";
axiosWithAuth()
.post(代理+url、{
用户名:loginCreds.username,
密码:loginCreds.password
})
。然后(res=>{
setItem(“token”,res.data.token);
props.history.push(“/dashboard”);
console.log(登录)
})
.catch(错误=>
setLoginCreds({
…loginCreds,
错误:“登录时出错。请重试。”
})
);
};
常量handleSubmit=e=>{
e、 预防默认值();
loginCreds.username==“”| | loginCreds.password==“”
?setLoginCreds({
…loginCreds,
错误:“请填写所有登录字段。”
})
:login();
};
返回(
输入登录凭据
登录
{loginCreds.err&&(
{loginCreds.err}
)}
);
};
导出默认登录;~~~
这是PrivateRoute.js
~~~从“React”导入React;
从“react router dom”导入{Route,Redirect};
从“./data/axiosWithAuth”导入axiosWithAuth;
/*
专用路线规则:
1.它具有与相同的API。
2.它渲染一个场景,并将所有道具传递给它。
3.它检查用户是否经过身份验证,如果是,则呈现
“组件”道具。如果没有,它会将用户重定向到/login。
*/
const privaterout=({component:component,…rest})=>{
//const Component=props.Component
返回(
axiosWithAuth(
) : (
)
}
/>
)
}
导出默认PrivateRoute

您可以将BrowserRouter替换为MemoryRouter。

您可以将BrowserRouter替换为MemoryRouter。

您可以使用状态检测用户是否经过身份验证,如果没有,则重定向。
比如说

this.state={
    loggedIn:false
}
render(){
    if(!this.state.loggedIn)
        return <Redirect to='/loginPage'>
    return <div>Is Logged in</div>
}
this.state={
洛格丁:错
}
render(){
如果(!this.state.loggedIn)
返回
返回已登录
}

有关更多信息,您可以使用google
React router guard

来检测用户是否经过身份验证,如果没有,则重定向。
比如说

this.state={
    loggedIn:false
}
render(){
    if(!this.state.loggedIn)
        return <Redirect to='/loginPage'>
    return <div>Is Logged in</div>
}
this.state={
洛格丁:错
}
render(){
如果(!this.state.loggedIn)
返回
返回已登录
}

有关更多信息,您可以通过谷歌
React路由器保护

,您可以参考React.Context API,该API用于帮助此类场景

在应用程序的引导过程中,您可以设置默认上下文,然后通过在组件中使用上下文来决定是呈现组件还是将用户重定向到主页,从而将上下文传递给各个组件


有关更多信息,请参考React.Context API,该API用于帮助此类场景

在应用程序的引导过程中,您可以设置默认上下文,然后通过在组件中使用上下文来决定是呈现组件还是将用户重定向到主页,从而将上下文传递给各个组件

更多信息