1

I'm an jQuery/Angular Developer last 5 years, and now I've planned move to ReactJS. I'm learning ReactJS by my own, as comparing the similar stuff what I did in jQuery (or Angular). My plan is, just to make a Login-Logout App, with ReactJS front-end and CodeIgniter - MySQL are the backend and database, respectively. Also I know what is CORS, and I'm pretty clear about the REST concepts. Let me explain my react app in detail.

My App component, calls an API via fetch, and upon the response which tells either session is set (as user is logged in) or session isn't set (user logged out/session expired), then the component will render either the 'Login Panel' component or a 'Dashboard' component. It works fine, as I tested. This is my App component.

class App extends Component {
    constructor(props) {
        super(props); //compulsary
        this.state = { isUserAuthenticated: false };
    }
    componentDidMount() {
        var innerThis=this;
        fetch('http://localhost/forReact/index.php/general/authenticate',{
          method:'GET',
          Content_type:'application/json',
          headers: {'Accept': 'application/json', 'Content-Type': 'application/json'},
          mode: 'cors',
          cache: 'no-cache'})
        .then(res => { return res.json() })
        .then(data => { alert(data.message); this.setState({isUserAuthenticated:data.result}); })
        .catch(err => console.error(err));
        }
        render() {
            return (this.state.isUserAuthenticated?<Home/>:<First/>);
        }
    }
    export default App;

This is my CodeIgniter Controller's relevant method (the controller name is General.php)

public function authenticate(){
    $session_data = $this->session->get_userdata();
    if (is_null($session_data)) {
        $this->sendJson(array("message"=>"No session","result"=>false));
    }
    else if (empty($session_data['username'])) {
        $this->sendJson(array("message"=>"No username index","result"=>false));
    }
    else if ($session_data['username']=="") {
        $this->sendJson(array("message"=>"Empty Username","result"=>false));
    }
    else{
        $this->sendJson(array("message"=>"Valid Session","result"=>true));
    }
}

This is the login component, which is being rendered in the App component, when there are no sessions set.

class LoginPanel extends React.Component {
  constructor(props) {
    super(props); //compulsary
    this.unRef = React.createRef();
    this.pwRef = React.createRef();
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleSubmit(){
    var toServer={"userName":this.unRef.current.value,"passWord":this.pwRef.current.value};
        fetch('http://localhost/forReact/index.php/general/login',{
          method:'POST',
          Content_type:'application/json',
          headers: {'Accept': 'application/json', 'Content-Type': 'application/json'},
          body: JSON.stringify(toServer),
          mode: 'cors',
          cache: 'no-cache'})
        .then(res => { return res.json() })
        .then(data => { alert(data.message); })
        .catch(err => console.log(err));
  }

  render() {
   return (
     <form onSubmit={this.handleSubmit}>
     <input ref={this.unRef} type="text" placeholder="Username"/>
    <input ref={this.pwRef} type="password" placeholder="Password"/>
    <button style={{margin:'1%'}} type="submit">Login</button>
    <button style={{margin:'1%'}} type="reset">Help</button>
     </form>);
   }
 }
export default LoginPanel;

Finally, this is the CodeIgniter Controller's relevant method (the same controller General.php)

public function login(){
    $arrived = json_decode(file_get_contents('php://input'), true);
    if (!empty($arrived['userName'])&&!empty($arrived['passWord'])) {
        $fromDB=$this->Mdl_general->login($arrived['userName'],$arrived['passWord']);
        if ($fromDB['result']) {
            $this->session->set_userdata('username',$arrived['userName']);
            $this->sendJson(array("message"=>$fromDB['message'],"result"=>$fromDB['result']));
        }
        else{
            $this->sendJson(array("message"=>"Username and or Password is/are incorrect!","result"=>false));
        }
    }
    else{
        $this->sendJson(array("message"=>"Invalid or Missing Input Parameters!","result"=>false));
    }
}

My issue is, when I logged in with the correct username and password (what I have in the mysql table), request was successfull and the response alert is showing; However, it seems the session is not set by the below php code,

$this->session->set_userdata('username',$arrived['userName']);

Whereas, if I did the above 'set session' code via a separate controller function, it sets the session successfully. However, even after that, the App component's API Call, still getting the response as the session is not yet set.

What might be the reason? I tried this via jQuery's Ajax Call and it works. I knew the fetch is much more different from the Ajax Call of jQuery. Could anyone explain, why this login component, didn't trig the PHP code to set the session?

1 Answer 1

1

That's not how it works. I will cut it to the short. The thing that you are trying to implement is not possible. In a very simple term, you are dealing with 2 different components now, your front end and the backend. And to communicate, you are using HTTP protocol as it is stateless every new request won't know anything about the previous one. In that case we need to reauthenticate every request. Check this comment to understand how to authenticate.

EDIT:

Just in case if you want to use REST

check this out

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer. It means that each and every API Call of Component, should have that authentication-token, then only it will communicate the backend well-enough?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.