简体   繁体   中英

Login page won't redirect to route to logged-in page

I've been struggling now with my login page to make the component render the Loggedin component. I'm having Reactjs for the frontend and a NodeJS backend. I'm fairly new to nodejs, express and react.

On the loginform component I do a post using fetch which passes the username and password to corresponding endpoint on the backend. No problem. At the backend it reads the jsonfile where i store users(not using any DB for this project) to find a match and if both username and password match the response it send is true. And i've tested that this works.

LoginForm Frontend:

 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); } }) }

I've been trying to make use of react-router-dom by experimenting. But no matter how i went with it the component for the logged in users never renders evens if resjson is true, not even the route changes to "localhost:3000/myAccount". I've also tried adding useHistory but that results in an invalid Hook when i add const history=useHistory();

Any ideas? If you need me to add anything else i'll do it, since i'm not that experience when it comes to JS i might have left something important out.

Thanks in advance!

Take a look below, i wrote explanations in comments:

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);
    }
  });

here is the link for the withRouter HOC use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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