登录页面不会重定向到路由到登录页面

时间:2020-08-11 17:15:50

标签: javascript node.js reactjs fetch react-router-dom

我现在一直在用登录页面进行挣扎,以使该组件呈现Loggedin组件。 我有用于前端的Reactjs和一个NodeJS后端。 我对Node.js很陌生,可以表达和做出反应。

在loginform组件上,我使用fetch进行了发布,它将用户名和密码传递到后端的相应端点。没问题。 在后端,它读取jsonfile,我将用户存储在其中(不使用任何数据库用于此项目)以查找匹配项,并且如果用户名和密码均匹配,则发送的响应为true。而且我已经测试过了。

LoginForm前端:

handleSubmit= (e) => {
    e.preventDefault()
    console.log(this.state)
    const { username, password} = this.state;
    const data = {username: username, password:password}
    
    fetch('http://localhost:3001/Login', {
          method: 'POST',
          mode:'cors',
          body: JSON.stringify(data),
          headers: {
            "Content-type": "application/json"
          }  
        })
        .then(function(res){
          return res.json()}).then(function(resjson){
            console.log(resjson);
            if (resjson){
              console.log(resjson);
              return<Redirect to='/myAccount'/>  
            }
            if(resjson==false){
              console.log(resjson);
            }
          })
           
        }

我一直在尝试通过尝试使用react-router-dom。但是,无论我如何处理,即使resjson为true,登录用户的组件也永远不会呈现偶数,甚至路由也不会变为“ localhost:3000 / myAccount”。 我也尝试添加useHistory,但是当我添加const history=useHistory();

时,这将导致无效的Hook

有什么想法吗?如果您需要我添加其他任何内容,我会做的,因为在JS方面我没有那种经验,所以我可能遗漏了一些重要内容。

谢谢!

1 个答案:

答案 0 :(得分:0)

下面看一下,我在评论中写了解释:

fetch("http://localhost:3001/Login", {
  method: "POST",
  mode: "cors",
  body: JSON.stringify(data),
  headers: {
    "Content-type": "application/json",
  },
})
  .then(function (res) {
    return res.json();
  })
  .then(function (resjson) {
    console.log(resjson);
    if (resjson) {
      console.log(resjson);
      // here you're returning a React Component and it could work inside  render !
      // return <Redirect to="/myAccount" />;

      // you could use history to redirect:
      // if you're inside a class component you could use withRouter HOC instead (there is a link below)
      return history.push("/myAccount");
    }
    if (resjson == false) {
      console.log(resjson);
    }
  });

这是 https://example.com/bar HOC使用的链接。