src/components/login/Login.js
/**
   * HTTP POST request is sent to the backend.
   * If the request is successful, a new user is returned to the front-end and its token is stored in the localStorage.
   */
HTTP POST request is sent to the backend.
If the request is successful, a new user is returned to the front-end and its token is stored in the localStorage.
HTTP POST request is sent to the backend . If the request is successful a new user is returned to the front - end and its token is stored in the localStorage .
login() {
    let status;
    fetch(`${getDomain()}/users/login`, {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      method: "POST",
      body: JSON.stringify({username: this.state.username, password: this.state.password})
    })
        .then(response => {
          status = response.status;
          return response.json();
        })
        .then(jsonResponse => {
          if (status === 404 || status === 401) {
            this.setState({"requestValid": false});
            return;
          } else if (status !== 200) throw new Error();
          this.setState({"requestValid": true});
          localStorage.setItem("token", jsonResponse.token);
          localStorage.setItem("id", jsonResponse.id);
          this.props.history.push(`/game`);
        })
        .catch(err => {
          if (err.message.match(/Failed to fetch/)) {
            alert("The server cannot be reached. Did you start it?");
          } else {
            alert(`Something went wrong during the login: ${err.message}`);
          }
        });
  }
login ( ) { let status ; fetch ( ` ${ getDomain ( ) } ` , { headers : { 'Accept' : 'application/json' , 'Content-Type' : 'application/json' } , method : "POST" , body : JSON . stringify ( { username : this . state . username , password : this . state . password } ) } ) . then ( response => { status = response . status ; return response . json ( ) ; } ) . then ( jsonResponse => { if ( status === 404 || status === 401 ) { this . setState ( { "requestValid" : false } ) ; return ; } else if ( status !== 200 ) throw new Error ( ) ; this . setState ( { "requestValid" : true } ) ; localStorage . setItem ( "token" , jsonResponse . token ) ; localStorage . setItem ( "id" , jsonResponse . id ) ; this . props . history . push ( ` ` ) ; } ) . catch ( err => { if ( err . message . match ( / Failed to fetch / ) ) { alert ( "The server cannot be reached. Did you start it?" ) ; } else { alert ( ` ${ err . message } ` ) ; } } ) ; }
HTTP POST request is sent to the backend.
HTTP POST request is sent to the backend .
// store the token into the local storage // user login successfully worked --> navigate to the route /game in the GameRouter