Проблема с session_start () PHP REACTJS AXIOS - PullRequest
0 голосов
/ 08 мая 2020

new result of the console на моей странице входа в мое веб-приложение, когда пользователь правильно вводит свой адрес электронной почты и пароль, открывается любой сеанс. В приложении консоли> у меня нет PHPSESSID. Однако, когда я использую свой файл PHP с простым кодом HTML, он работает правильно, и у меня есть PHPSESSID. Я не понимаю, в чем проблема, если кто-нибудь может мне помочь?

ReactJS файл:

import React from 'react';
import { Redirect} from 'react-router';
import './connexion.css';
import axios from 'axios';

class Login extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      password: null,
      email: null,
      loggedIn: false, 
      error: '',

    };
  }

  change = async e => {
    await this.setState({
      [e.target.id]: e.target.value,
    });
  }

  handleSubmitLogIn = e => {
    const { email, password } = this.state;

    if (password && email) {

      console.log(this.state);
      let formData = new FormData();
      formData.append("email",this.state.email);
      formData.append("password",this.state.password);
      const url = "http://localhost:8888/API/Connexion/login.php";
      axios.post(url, formData)

      .then(function(response) {  
        this.setState({loggedIn: true});
        console.log("success");
      }.bind(this))

      .catch((error) => {
        if(error.response && error.response.status === 403){
          this.setState({
            error: error.response.data,
            });
        }
      });

    } else {
      this.setState({
        error: 'please fill in everything',
      });
    }

    setTimeout(() => {
      this.setState({
        error: '',
      });
    }, 2000);

    e.preventDefault();    
  }


  render() {
    const { error } = this.state;
    const {loggedIn } = this.state;

    if(loggedIn){
      //redirect to the home page
      return <Redirect to="/accueil"/>;
    }

    return (
      <div>
                <form onSubmit={this.handleSubmitLogIn}>
                  <div className="text-center">
                    <h2 className="dark-grey-text mb-5">
                      Log In
                    </h2>
                  </div>
                  <label htmlFor="email" className="grey-text">
                    email
                    <input
                      type="email"
                      id="email"
                      name="email"
                      className="form-control"
                      onChange={this.change}
                    />
                  </label>

                  <br />
                  <label htmlFor="password" className="grey-text">
                    password
                    <input
                      type="password"
                      id="password"
                      name="password"
                      className="form-control"
                      onChange={this.change}
                    />
                  </label>

                  <div className="text-center mb-3">
                    <button type="submit" className="btn btn-primary" onClick={this.handleSubmitLogIn}>validate</button>
                    {
                     error && (
                     <p className="error">{error}</p>
                     )
                    }
                  </div>
                </form>
      </div>
    );
  }
}

export default Login;

PHP файл логин. php:

<?php
    session_start();        

    $con=mysqli_connect('localhost', 'root', 'root', 'mybibli');

    if(!$con) {                                                 
        die('erreur de connexion avec la base de donnée'.mysql_error());    
    }

        $email = $_POST['email'];
        $password = $_POST['password'];

        $email = strip_tags(mysqli_real_escape_string($con, trim($email)));
        $password = strip_tags(mysqli_real_escape_string($con, trim($password)));       

        $query = "SELECT * FROM user where email='".$email."'"; 
        $hi = mysqli_query($con, $query);
        if(mysqli_num_rows($hi) > 0) {

            $row = mysqli_fetch_array($hi);
            $password_hash = $row['password'];

            if(password_verify($password, $password_hash)) {
                $_SESSION['User']=$_POST['email'];      
                http_response_code(200);            
            } else {
                echo"invalid password";
                http_response_code(403);            
            }
        } else{
            echo"No user account linked to this email address";
            http_response_code(403);            
        }
?>

1 Ответ

0 голосов
/ 08 мая 2020

Внимательно прочтите советы отсюда Сделайте Axe ios автоматически отправлять куки в своих запросах . Я не хочу дублировать это, но вам нужно добавить withCredentials: true к вашему запросу ax ios, и вы должны добавить заголовок к своему ответу Access-Control-Allow-Origin: http://localhost:8888 в вашем случае. Это все, что вам нужно.

...